Wednesday 18 February 2009

C# Extention methods

This is a way of extending a class by adding methods to it. Heres a sample extention method class.

namespace ExtentionMethodSample
{
public static class ExtentionMethodSampleClass
{
public static Int32 myToInt32(this string s)
{
return Convert.ToInt32(s);
}
}
}


This example method adds a new method called "myToInt32" to the standard "string" class. This method will appear in intellisense.

In this case it simply allows you to convert a string to an Int32, which is a bit daft, but it could do any number of things. For instance it might return -1 if the string is empty. You can put any code into the method.

Another example is you might extend the DataRow class to return a Company object, as an alternative to creating a class that requires a DataRow in its constructor.

Another sample I've seen is where "string" was extended to give it a method to return only the numeric parts of the strings contents.