Extension Methods in C#

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

What’s the Specification of an Extension Method?

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: x is an object from int class and we called it as an instance method in int class.

How 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).

 Collapse | Copy Code
public static class MyMathExtension 
{ 
    public static int factorial(this int x) 
    { 
        if (x <= 1) return 1; 
        if (x == 2) return 2; 
        else 
            return x * factorial(x - 1); 
    } 
}

Why Do We Need Extension Methods?

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 int class in .NET by adding a factorial method to it using recursion technique.

One way of thinking is to inherit int 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.

Using extension methods, you can use your new methods as a part of int class in .NET.

In the above screen shot, I wrote the following line of code:

int x = 3;
x.factorial();

Factorial method becomes a part of int class by implementing factorial method as an extension method in my class without inheriting int class in .NET, see below (Figure 1.1).

General Tips in Extension Methods Usage

This section is optional reading section for understanding the core idea of extension methods:

  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#, forexample:
     Collapse | Copy Code
    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.

  3. It is important to note that extension methods can’t access the private methods in the extended type.
  4. 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.
  5. 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.

===========================================================================================

You cannot add methods to an existing type, you can only add methods that appear to be a member of the existing type through extension methods. Since this is the case you cannot add static methods to the type itself since extension methods use instances of that type.

There is nothing stopping you from creating your own static helper method like this:

static class DateTimeHelper
{
    public static DateTime Tomorrow
    {
    	get { return DateTime.Now.AddDays(1); }
    }
}

Which you would use like this:

DateTime tomorrow = DateTimeHelper.Tomorrow;
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s