Code Heaven For C# Developer

Wednesday, May 18, 2011

Extension Methods in C#

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.

An extension method is a special kind of static method that allows you to add new methods to existing types without creating derived types.

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


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);
}
}


Complete Code for My Demo

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int x = 3;
Console.WriteLine(x.factorial());
Console.ReadLine();
}
}
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);
}
}
}

Cheers....!!!!!!!

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home