Wednesday, 20 August 2014

Extension Methods in C#


 
While designing your classes in .NET projects, we used to have sibling classes which do simple operation from its parent classes to add a kind of customization for parents’ methods. Suppose that you want to extend string class in .NET by adding a WordCount method to it .
One way of thinking is to inherit string class and add your new method to it and use your new methods in your code. This is a valid solution but let us see what extension methods can provide us.

An extension method is a special kind of static method that allows you to add new methods to existing types without creating derived types.
The extension methods are called as if they were instance methods from the extended type, For example: str  is an object from string class and we called it as an instance method in string  class.
Code to Create my Extension Method:
Simply, you create your own static method in your class and put this keyword in front of the first parameter in this method (the type that will be extended).
public static class MyExtensions
{
    public static int WordCount(this String str)
    {
        return str.Split(new char[] { ' ', '.', '?' },
                         StringSplitOptions.RemoveEmptyEntries).Length;
    }



Points To remember while creating Extension method:
  1. This keyword has to be the first parameter in the extension method parameter list.
  2. Extension methods are used extensively in C# 3.0 and further version specially for LINQ extensions in C#, for example:
int[] ints = { 10, 45, 15, 39, 21, 26 };

var result = ints.OrderBy(g => g);
Here, order by is a sample for extension method from an instance of IEnumerable<T> interface, the expression inside the parenthesis is a lambda expression.
  1. It is important to note that extension methods can't access the private methods in the extended type.
  2. If you want to add new methods to a type, you don't have the source code for it, the ideal solution is to use and implement extension methods of that type.
  3. If you create extension methods that have the same signature methods inside the type you are extending, then the extension methods will never be called.

The WordCount extension method can be brought into scope with this using directive:
using ExtensionMethods;
 
And it can be called from an application by using this syntax:
 
string s = "Hello Extension Methods";
        int i = s.WordCount();
 

In your code you invoke the extension method with instance method syntax. However, the intermediate language (IL) generated by the compiler translates your code into a call on the static method. Therefore, the principle of encapsulation is not really being violated. In fact, extension methods cannot access private variables in the type they are extending.

No comments:

Post a Comment