Tuesday, June 30, 2009

Extension Method

This is the new feature of C# 3.0

Static method can invoke using instance method syntax.

static class contain a parameter with this key word.

E.g:

public static class NewFeature

{

public static int TointNewFeature(this int i,int j)

{

return i+j;

}

public static int TointOldFeature(int i, int j)

{

return i+j;

}

}

class App

{

static void Main()

{

int iDemo = 2.TointNewFeature(3);

Console.WriteLine(iDemo);

iDemo = NewFeature.TointOldFeature(2,3);

Console.WriteLine(iDemo);

}

Features of Extension Method

  • Contains the keyword this
  • here the parameter can be leave.ie parameter should not be provided
  • can be called only by an instant variable.

In ILDASM you can see system.runtime.compilerservices .extensionAttribute for the

TointNewFeature method.ie during runtime the extension is flagged and do the rest of operation.

0 comments:

 
Counter