Monday 3 September 2012

Extension Methods

In typical Object Oriented developement, extending an existing type is achieved through creating derived types. But consider a scenario where the base type is not inheritable or sealed, in that case there is no way to extend these types. An example of such type is the System.String class.

With the launch of  Microsoft .Net Framework 3.0, it was made possible. A new feature named Extension Methods was introduced to lets you extend any existing type's functionality, even when a type is not inheritable. And these extension methods play a crucial role in the implementation of LINQ.
  • Extension methods allow you to add new method(s) to an existing type without creating a new derived type or recompiling the old type.
  • Extension methods can be written for Value, Reference and Interface types.
  • Extension methods are a special kind of static method, but they are called as instance method.
  • Extension methods create the illusion that they are defined on a real type, but in reality, no changes are made to the original types.
  • Extension methods cannot access private variables of the type they are extending.
  • The most common Extension methods are the LINQ standard query operators that add query functionality to the existing System.Collections.IEnumerable and System.Collections.Generic.IEnumerable<T> types.
It is not a standard object-oriented concept; it is a specific Microsoft® .NET Framework implementation feature that opens up a new set of possibilities. It's worth noting that the intermediate language (IL) generated by the compiler translates your code into a static method call. Therefore, the principle of encapsulation is not really being violated.

 

Creating Extension Methods:

In general, you will probably be calling extension methods far more often than implementing your own.

1. Create a Class Library with the name StringExtensions.


2. Add reference to System.Core.dll. This reference is required because the compiler needs System.Runtime.CompilerServices.ExtensionAttribute for creating the extension methods. In C#, you do not need to write this attribute; you should use the this modifier for the first parameter to create an extension method. The compiler automatically emits ExtensionAttribute for extension methods.

3. Define a static class with the name StringExtension to contain the extension methods. The class must be static and visible to client code. For more information about accessibility rules, see Access Modifiers.

4. Implement the extension method as a static method with at least the same visibility as the containing class. The first parameter of the method specifies the type that the method operates on; it must be preceded with the this modifier.


5. Build the project.

 

Calling Extension Methods:

1. Create a Console Application with the name StringExtensionTest.


2. Add reference to previously created assembly named StringExtensions.

3. Add a using directive to specify the namespace that contains the extension methods. Extension methods come into scope at namespace level. It means all the extension methods of all the classes defined in a namespace will brought into scope with this using directive.

4. Create the object of class and you will start seeing the extension methods in IntelliSense for this object.

5. Note that the first parameter is not specified by calling code because it represents the type on which the operator is being applied, and the compiler already knows the type of your object. You only have to provide arguments for parameters 2 through n.



6. Run the application.

 

Compilation & Binding of Extension Methods:

1. Extension methods are used to extend a class or interface, but not to override them.

2. An extension method with the same name and signature as an interface or class's instance method will never be called.

3. At compile time, extension methods always have lower priority than instance methods defined in the type itself. In other words, if a type has a method named Process(int i), and you have an extension method with the same signature, the compiler will always bind to the instance method.

4. When the compiler encounters a method invocation, it first looks for a match in the type's instance methods. If no match is found, it will search for any extension methods that are defined for the type, and bind to the first extension method that it finds.

5. At the time of actual compilation, the extension method call gets converted to static method call. So the intermediate language (IL) generated after compilation, has a static method call corresponding to an extension method.

 

Security:

Extension methods present no specific security vulnerabilities, because they cannot access any private data in the extended class.

 

Guidlines:

In general, Microsoft recommend that you implement extension methods sparingly and only when you have to. Whenever possible, client code that must extend an existing type should do so by creating a new type derived from the existing type. For more information, see Inheritance.

When using an extension method to extend a type whose source code you cannot change, you run the risk that a change in the implementation of the type will cause your extension method to break.

If you do implement extension methods for a given type, remember the following two points:
  • An extension method will never be called if it has the same signature as a method defined in the type.
  • Extension methods are brought into scope at the namespace level. For example, if you have multiple static classes that contain extension methods in a single namespace named Extensions, they will all be brought into scope by the using Extensions; directive.

 

Framework:

.Net 3.0, 3.5, 4.0, 4.5

10 comments:

  1. good one pushpu...keep it up!!!

    ReplyDelete
  2. Nice post...thanks for information sharing.

    ReplyDelete
  3. Cool. Concise and thorough. why dont you post some articles on Framework 4.5?

    ReplyDelete
  4. Nice post!!!
    looking forward for more posts on how extension methods work internally.

    Thanks,
    Chandan

    ReplyDelete
    Replies
    1. Thanks Chandan.

      See from execution point of view there is nothing special happening internally, its just a static method call.

      At the time of compilation, the extension method call gets converted to static method call. So to be precise in IL, an extension method is like any another static method.

      Delete