public static IEnumerable
this IEnumerable
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
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