Monday, August 27, 2012

.NET : Extension Method

An Extension method is a new language feature of C# starting with the 3.0 specification, as well as Visual Basic.NET starting with 9.0. Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. An extension method is a static method of a static class that you can call as though it were an instance method of a different class. 
For example, you could create an extension method named ToDouble that is a static method in a static class you create named StringConversions, but that is called as though it were a method of an object of type string.
Extension Method Declarations and Invocations:
Specifying a method’s first argument with the this keyword modifier will make that method an extension method. The extension method will appear as an instance method of any object with the same type as the extension method’s first argument’s data type. For example, if the extension method’s first argument is of type string, the extension method will appear as a string instance method and can be called on any string object. Also, extension methods can only be declared in static classes.
Example of an extension method:
namespace Netsplore.Utilities
    public static class StringConversions
        public static doubleToDouble(this string s)
            return Double.Parse(s);
        public static boolToBool(this string s)
            return Boolean.Parse(s);
Here both the class and every method it contains are static. ToDouble is an extension method, because method is static and its first argument specifies the this keyword.
Calling an extension method:
    double pi = "3.1415926535".ToDouble();
This produces the following results:
Extension Method Precedence:
Normal object instance methods take precedence over extension methods when their signature matches the calling signature. Extension methods seem like a really useful concept, especially when you want to be able to extend a class you cannot, such as a sealed class or one for which you do not have source code. The previous extension method examples all effectively add methods to the string class. Without extension methods, you couldn’t do that because the string class is sealed.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.