Generic Free Pattern

Hello, below you can find C# 2.0 Generic Free Pattern example that I just invented ;). Only generic code is invoked but it is called like without generic type. I have better idea of implementation of this pattern but it needs introduction of 3rd usage of out keyword in C# and I cannot make it. However I could made this pattern and I hope you like it. Now you can write generic code that is used like no generic needed, so it is like JavaScript in C# when you use it and strong typed generics when you write it ;).

namespace GenericFreePattern
{
    using System;

    // Framework Code
    internal class Comparer<T> : Comparer where T : IComparable, IComparable<T>
    {
        public Comparer(T x1, T x2)
        {
            this.x1 = x1;
            this.x2 = x2;
        }
        
        private readonly T x1;
        private readonly T x2;
        
        public override int Compare()
        {
            return x1.CompareTo(x2);
        }
    }

    public class Comparer
    {
        internal Comparer() {}

        private readonly Comparer instance;
        
        public Comparer(IComparable x1, IComparable x2) {
            if (x1.GetType() != x2.GetType())
                throw new InvalidOperationException(
                    "Arguments have different types!");
            
            instance = (Comparer)Activator.CreateInstance(
                typeof(Comparer<>)
                .MakeGenericType(x1.GetType()),
                new object[]{x1, x2});
        }
        
        public virtual int Compare()
        {
            return instance.Compare();
        }
    }
            
    // Client Code
    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine(
                "new Comparer(3,5).Compare() = {0}",
                new Comparer(3,5).Compare());
            Console.Write("Press any key to continue...");
            Console.ReadKey(true);
        }
    }
}

P ;).

One Reply to “Generic Free Pattern”

  1. Pingback: Third usage of C# out keyword with Roslyn Intro @ coding by to design

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.