Friday, April 22, 2016

Extension Methods in C#

Suppose you have created a class where operations are performed on class fields using public methods.

If you want to add more methods to extend the functionality of this class, you will typically create a child class, write a method in child class and use this class whereever required.

With extension methods you don't need to create a child class. It enables you to add methods to existing types (classes) without creating a new derived type, recompiling, or otherwise modifying the original type.
Extension methods are actually static methods but of special type. They are called as if they were instance methods on the extended type.

They are introduced in C# from 3.0 version.

They are only in scope when the namespace in which  they are defined is explicitly imported into the source code with a using directive.

Example - LINQ methods like GroupBy(), OrderBy(), Average(), are extension methods on IEnumerable<T> types like List<T> or Array.
They are not defined in these types but can be accessed using dot operator on list objects.

Example -
class MyExtensionMethod
{
    static void Main()
    {          
        int[] arr = { 10, 45, 15, 39, 21, 26 };
        var result = arr.OrderBy(s => s); 
        foreach (var i in result)
        {
            Console.Write(i + " ");
        }        
    }      
}

Output - 10 15 21 26 39 45

Here OrderBy() method is an extension method.

Create your own extension method -
--------------------------------------
namespace MyExtensions
{
    public static class MyExtensionsMethod
    {

//Extension Method
        public static int WordCount(this String str)
        {
            return str.Length;
        }
    }
}

Parameter in public static int WordCount(this String str) i.e. specifies which type the method operates on, and the parameter is preceded by the this modifier.

And it can be called from an application as below:
using MyExtensions;
string s = "Hello Extension Methods";
int i = s.WordCount();

Note -
1. Extension methods cannot access private variables in the type they are extending.

2. An extension method with the same name and signature as an interface or class method will never be called. 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.


Please share your views about this post.

No comments:

Post a Comment