Extension Methods in C#

Introduction

In this article, I would like to introduce one of the new C# 3.0 enhancements “Extension Methods” and so on. This feature is available in C # 3.0 compilers and further versions (C# 4.0); this feature is very important for all developers especially if you would like to use the dynamism of the C# enhancements to take place in your class design.

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

Figure 1.1 of extension method

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