Extension method

  • Extension Methods have to be implemented as static methods and in static classes (inside a non-nested, non-generic static class to be more precise).
  • You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself.
  • Extension methods cannot access private variables in the type they are extending.

 

class Program
{
static void Main(string[] args)
{
string str = “hi”;
str.M2();
// wether Method M1 is not accessable to str because ‘this’
}
}
public static class MyClass
{
public static int M1( string data)
{
return (Convert.ToInt32(data));
}

public static int M2(this string data)
{
return (Convert.ToInt32(data));
}
}

for more info :

http://msdn.microsoft.com/en-us/library/bb383977.aspx

http://www.codeproject.com/KB/cs/ExtensionMethodsCSharp.aspx

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s