Raj Aththanayake's Blog Raj Aththanayake's Blog | A tip on type Inference in Generic Methods
Home > C#

A tip on type Inference in Generic Methods

5. May 2011

As you may already know C# support type interfaces for generic methods. I have seen many developers write code like below for both extension methods and generic methods.

   1: public static bool IsGreaterThan<T>(T x, T y) where T : IComparable<T>
   2:         {
   3:             if (x.CompareTo(y) > 0)
   4:             {
   5:                 return true;
   6:             }
   7:  
   8:             return false;
   9:         }

Extension method:

   1: public static bool IsGreaterThanExt<T>(this T x, T y) where T : IComparable<T>
   2:         {
   3:             if (x.CompareTo(y) > 0)
   4:             {
   5:                 return true;
   6:             }
   7:  
   8:             return false;
   9:         }

The Usage:

   1: Console.WriteLine(IsGreaterThan<int>(4, 3));
   2:  
   3: Console.WriteLine(4.IsGreaterThanExt<int>(3));
   4:  

The above <int> is redundant. The reason is that the type is automatically inferred by the C# compiler.

Now you can simply call the methods without the type <T>

 

   1: Console.WriteLine(IsGreaterThan(4, 3));
   2:  
   3: Console.WriteLine(4.IsGreaterThanExt(3))

 

C#

Comments are closed