Wednesday, June 13, 2012

Extension Methods in C#

In this post, we will take a look at what extension methods are and how to use them in C#. Extension methods are one of the best things that have been introduced in .Net framework in terms of readability. Extension methods are available from .Net framework 3.5.



Extension Methods

Extension methods allow you to extend a type, such as integer or string, without re-compiling or modifying the type. In other words, Extension methods allow you to "add" method(s) to exixting type without creatimg new derived type or modifying the original type.They can be implemented on any type in the .NET Framework or any custom type that you define.

Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

How Do We Create Extension Methods?

The basic outline of creating extension methods goes something like this:
  1. Create a public static class.
  2. Create a function that you wish to perform
  3. Make that function an extension method.
Here I will now demonstrate how to create a extension method that will return the factorial of a number.
Using the list above, I must first create a b public static class
public static class MyExtensions
{

}

The next step would be to write the function that we are going to need, which in this case is the following:
public static class MyExtensions
{
    public int Factorial(int number)
    {
        if(number==1)
        {
            return number;
        }
        else
        {
            return number * Factorial(number-1);
        }
    }
}

To make our C# version of our function, we need an extension method to mark the function as static (so that it can be accessed at any time without the need for declaring anything) and secondly, mark the first parameter with the this keyword. This keyword basically tells the CLR that when this extension method is called, to use "this" parameter as the source. See the following:
public static class MyExtensions
{
    public int Factorial(this int number)
    {
        if(number==1)
        {
            return number;
        }
        else
        {
            return number * Factorial(number-1);
        }
    }
}

After creating the extension method , you will see this:-
Extension Method

Hopefully, you now have an understanding of how to implement extension methods in C#. If you need any help with your extension methods or if you would like to ask a question, drop me a comment below.


References:-

No comments:

Post a Comment

If You Enjoyed This Post Please Take 5 Seconds To Share It.

^ Scroll to Top hgpromo