A tip on type Inference in Generic Methods

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.

public static bool IsGreaterThan<T>(T x, T y) where T : IComparable<T>
{
      if (x.CompareTo(y) > 0)
      {
          return true;
      }

      return false;
 }

Extension method:

public static bool IsGreaterThanExt<T>(this T x, T y) where T : IComparable<T>
           {
               if (x.CompareTo(y) > 0)
               {
                   return true;
               }

               return false;
           }

The Usage:

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

The above 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

Console.WriteLine(IsGreaterThan(4, 3));
Console.WriteLine(4.IsGreaterThanExt(3))

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s