Tuesday 28 April 2009

Extension Methods in C# 3.0

A new function of C# 3.0 is Extension Methods.

"Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type."

For example, if you wanted a method to convert a temperature from celsius to fahrenheit, where previously you would use

int temp = 30;
int i = myClass.CelsiusToFahrenheit(temp);


using extension methods you can now use

int temp = 30;
int i = temp.CelsiusToFahrenheit();

To do this you would create a new static class to contain the static method CelsiusToFahrenheit. The key to extension methods is passing in the this keyword along with the variable. For example,


public static class myClass
{
public static int CelsiusToFahrenheit(this int temp)
{
return (9 / 5) * temp + 32;
}
}


This will now allow you to use the CelsiusToFahrenheit method on any integer variables.

You can also add methods to extend your own custom classes, and the methods can have different return types. For example, if you have your own class, TestClass, you can create a static method using extending TestClass, e.g.


public static DateTime doSomething(this TestClass t)
{
//do something
}


Which will then allow you to use:

TestClass t = new TestClass();
DateTime x = t.doSomething();

No comments:

Free Hit Counter