This is a back to basics post.

As you may already know, C# compiler don’t support type inference for generic classes, but it supports type inference for generic methods. To illustrate the point, let us consider a very simple example.

class Program
    {
        //Our generic IsGreaterThan method
        public static bool IsGreaterThan<T>(T x, T y) where T : IComparable<T>
        {
            return (x.CompareTo(y) > 0);
        }

        static void Main(string[] args)
        {
            //You don't need to explicitly specify IsGreaterThan<int>
            var result = IsGreaterThan(20,10);
            Console.WriteLine(result); 
        }

    }

As you can see, we are not specifying the type explicitly, while calling our IsGreaterThan method - it is inferred automatically by the compiler. That is simple, isn’t it? Now, things become a a bit more interesting when you combine Generic method type inference with extension methods. Have a look at this code, we just made our IsGreaterThan<T> method an extension method.

  public static class UtilExtensions
    {
        //Our generic IsGreaterThan extension method
        public static bool IsGreaterThan<T>(this T x, T y) where T : IComparable<T>
        {
            return (x.CompareTo(y) > 0);
        }      
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            //You still don't need to explicitly specify IsGreaterThan<int>
            var result = 20.IsGreaterThan(10);
            Console.WriteLine(result);

        }

    }

As you can see, we are still good - the compiler can still infer the types. And of course, you can leverage our IsGreaterThan against any IComparable implementation. Also, explore more back to basics posts.


blog comments powered by Disqus
top