Saturday, August 11, 2012

Extension Methods

Extension methods allows you to add methods to existing types without creating any derived type. So we don't have to modify the original type.Extension methods are special kind of static method, but they can called as instance methods on the extended type.

  • Extension class and the extension method should be static.
  • The first parameter specifies which type the method operates on.
  • The first parameter is preceded by the this modifier.

Extension methods are only in scope when you explicitly import the namespace in to your source code with a using directive.

Extension Methods for Existing Types

Below extension method has written for the string type.
You can invoke the extension method as a instance method or a static method.

Extension Methods for Classes

In the below code I have write a interface. But without changing the current implementation I'll add a Extension class. By doing so, we can call the extension methods which are like members of the interface.

Extension Methods for Lambda Expressions

Extension methods can be used for the LINQ/Lambda expressions. Below I have created some extension methods for the List<Student>.