Tuesday 2 September 2008

What's New C# 3: Extension methods

Extension methods allows developer to add extra method to an existing class without creating a derivative of it or without modifying the original class code. Lets take an example of the standard C# library String class. We want to add a method to validate if the string length is zero or not. An extra method can be added to this class by simple implementing a method using extension method syntax. Extension method signature looks like this :

static <returnType> methodName( this CalssToExtend thisObject, additional parameters list.....)

{

methods body

}

So in our example of string class if we add a method called IsZero to return true when check passed; it will look like


public static bool IsZero( this string thisObj )

{

return thisObj.Length== 0;

}
The 'this' word before the first parameter in the method identifies which class this method relates to. In this case it's string class.

A working example is as follows.

=====================

using System.Collections.Generic;

namespace ConsoleApplication1
{
public static class Program
{
private static void Main(string[] args)
{
var postcode = "SL2 8FF";
var flag = postcode.IsPostcode();
// var costs = new List();
// var sum = costs.
}
}

static class Extension
{
///
/// An extension method to String class to check whether this string is a postcode.
///

///
///
public static bool IsPostcode(this string input)
{
return false;
}

///
/// And extension method to List to return sum of all entry of the list
///

///
///
public static double Sum( this IList inputList )
{
var sum = 0.0;
foreach( var item in inputList )
sum += item;
return sum;
}
}
}

====================

Few points to remember:


  • Extension method implementer class has to be static class.

  • All extension methods must be static

Advantage:



  • Don't need to derive a class to extend it. This is specially useful when a class is not derivable.

  • Methods are visible in intellisense drop down menu.

  • Extension can be added to interfaces. When a extension is added to a Interface it's applied/available to all its derive classes.

No comments:

Post a Comment