Extension Methods in C#

0

Category :

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

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).
public static class MyExtension 
{ 
    public static int factorial(this int x) 
    { 
        if (x <= 1) return 1; 
        if (x == 2) return 2; 
        else 
            return x * factorial(x - 1); 
    }

    public static IEnumerable> Combinations(this IEnumerable elements, int k)
    {
        return k == 0 ? new[] { new T[0] } :
            elements.SelectMany((e, i) =>
            elements.Skip(i + 1).Combinations(k - 1).Select(c => (new[] { e }).Concat(c)));
    }
}
Usage
int x = 3;
x.factorial();
Combinations Usage

List td = new List();
td.Add(new TransportDetails() { MaxPax = 8, Price = decimal.Parse("88.04") });
td.Add(new TransportDetails() { MaxPax = 20, Price = decimal.Parse("128.70") });
td.Add(new TransportDetails() { MaxPax = 31, Price = decimal.Parse("161.37") });

var res = td.Combinations(2);

General Tips in Extension Methods Usage

  1. This keyword has to be the first parameter in the extension method parameter list.
  2. It is important to note that extension methods can't access the private methods in the extended type.
  3. 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.
  4. 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.
my thanks to:
http://www.codeproject.com/Articles/34209/Extension-Methods-in-C
http://msdn.microsoft.com/en-us/library/bb383977.aspx
http://www.blackwasp.co.uk/ExtensionMethods.aspx
http://www.extensionmethod.net/
101-LINQ-Samples

0 comments:

Post a Comment