Tuesday, 24 July 2012

Extension Methods:

Previously you understood how the query operators such as StartsWith can be used with the dot notation. You might wonder where these methods come from. These methods, which reside in the System.Query.Sequence class, are part of a new feature in C# 3.0 called Extension Methods. Extension Method is a new way of extending existing types. Basically, this works by adding a "this" modifier on the first argument. For example, the Sequence class has the Where operator defined as follows:

public static IEnumerable Where(
this IEnumerable source, Func predicate) {
foreach (T element in source) {
if (predicate(element)) yield return element;
}
}

Note the use of "this" modifier on the first argument. The compiler sees this and treats it as a new method on the specified type. So now IEnumerable gets the Where() method. Here it is important to remember that the explicitly defined methods in the object get the first priority. For example, if you call Where() on an object, then the compiler goes to find Where() on the object itself first. If Where() is not present, then it goes off to find an Extension Method that matches the method signature. Clearly, while this feature is cool and really powerful, extension methods should be used extremely sparingly.

Note that C# 3.0 also makes it possible to add methods to existing classes that are defined in other assemblies. All the extension methods must be declared static and they are very similar to static methods. Note that you can declare them only in static classes. To declare an extension method, you specify the keyword "this" as the first parameter of the method, for example:

public static class StringExtension
{
public static void Echo(this string s)
{
Console.WriteLine("Supplied string : " + s);
}
}

The above code shows the extension method named Echo declared in the StringExtension class. Now you can invoke the Echo method like an instance method with a string. The string is passed with the first parameter of the method.

string s = "Hello world";
s.Echo();

Based on the above code, here are the key characteristics of extension methods.

Extension methods have the keyword this before the first argument
When extension methods are consumed, the argument that was declared with the keyword this is not passed. In the above code, note the invocation of Echo() method without any arguments
Extension methods can be defined only in a static class
Extension methods can be called only on instances. Trying to call them on a class will result in compilation errors. The class instances on which they are called are determined by the first argument in the declaration, the one having the keyword this.

No comments:

Post a Comment