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.
It represents static
methods as instance methods. An extension method uses the this-keyword in its
parameter list.
It must be located in
a static class and static method.
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).
namespace LooslyCoupled
{
public static class MyMathExtension
{
public static int? NullCheck(this int? x)
{
return x == null ? 0 : x;
}
}
}
namespace LooslyCoupled
{
class Program
{
static void Main(string[] args)
{
int? a = 100;
int? b=a.NullCheck();
Console.WriteLine("Value A =
"+ a.NullCheck());
Console.WriteLine("Value B =
" + b);
a = null;
Console.WriteLine("Value A is
null = " + a.NullCheck());
Console.Read();
}
}
}
General
Tips in Extension Methods Usage
This
section is optional reading section for understanding the core idea of
extension methods:
a. This keyword has to be the first parameter in the
extension method parameter list.
b. Extension methods are used extensively in C#
3.0 and further version specially for LINQ extensions in C#, for example:
int[] aa = { 1, 4, 5, 3, 2, 6 };
var result = aa.OrderBy(g =>
g);
Here,
order by is a sample for extension method from an instance of IEnumerable interface, the expression inside the parenthesis is a lambda
expression.
c. It is important to note that extension methods
can't access the private methods in the extended type.
d. 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.
e. 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.