Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Extension Methods in C#

0.00/5 (No votes)
18 Jan 2013 1  
Extension methods in C#

This feature is fascinating. Extension methods give us the ability to include custom methods with the existing types w/o inheriting the actual type. It gives you the ability to invoke the methods as if they are instance methods on the actual type. But at compile time, an extension method has lower priority than the instance methods. Suppose you created an extension method name IsNullOrEmpty for the type String. The method invocation will always pick the one which is in the instance and ignore your extension method.

Though they are extending the instance type with methods, these methods are never have the ability to access the private members or methods of the type.

See this example:

namespace ExtensionMethods {
  public static class Extensions {
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek) {
      int diff = dt.DayOfWeek - startOfWeek;
      if (diff < 0) {
        diff += 7;
      }
      return dt.AddDays(-1 * diff).Date;
    }
  }
}

It will return the date of start of the week. You can invoke this method like this:

DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);

So to define extension method with few words, we can say:

  • They are static methods.
  • First parameter of the method must specify the type that it is operating on. Proceed with the ‘this’ modifier.
  • Ignore first parameter during invocation.
  • Call the methods as if they were instance methods on the type.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here