Translate

Wednesday, 22 April 2009

Extension Methods

An ExtensionMethod is a great technique introduced in .Net 3.x that extends on the existing capability of a type.

The syntax required by an Extension Method is that it should be static and cannot be created inside a non-generic static class. The method should consist of a parameter of that type for which this method is an extension of.

Syntactically, it means that the parameter should be prefixed with the "this" keyword followed by the type and identifier. For example, if you want to create an extension method for a type called "MyClass" then an extension method can be created in another class as below:

public static class MyExtendingClass{
public static void MyExtensionMethodForMyClass(this MyClass obj){
// Some statements
}
}

The below example extends the System.Int32 class and provides for an extension method called "IsInString". So, when a call to Convert.ToInt32() works on a string, the resultant integer will be provided with the newly created extension method as well.

using System;
namespace ExtensionMethodsExample
{
public static class ExtensionsClass
{
public static bool IsInString(this object o)
{
if (o is Int32)
{
int i = (int)o;
Console.WriteLine("Parameter passed is an integer type" + i);
}
if (o.Equals("24"))
return true;
return false;
}
}

public static void Main(){
Console.WriteLine((Convert.ToInt32("22") + Convert.ToInt32("2")).IsInString().ToString());

}
}

No comments: