Sunday, November 25, 2007

Extension Methods: C# 3.0

A new feature in C# 3.0 is extension methods. I must say I like extension methods - very much. They allow you to extend any type transparently (without having to derive from it). The best thing is, this is not a .NET 3.5 feature, in other words it doesn't require .NET 3.5, but *does* require the C# 3.0 compiler. So if you want to implement this functionality today, your users do not require .NET 3.5.

How many times have you wanted to check a value type such as an integer for nulls or zeros with ease. Previously you would've had to write something like the following:

Note: the ? indicates a nullable generic.

int? i = 0;

if (i == null || i == 0)
//Do something


The above code is fine, but we can simplify it.

Here's a simple example of its use:

1. Define a static class, the name doesn't really matter but the class must be static.

public static class IntHelper
{
}


2. Now implement a new method as follows:


public static class IntHelper
{
public static bool IsNullOrZero(this int? i)
{
if (i == null || i == 0)
return true;
else
return false;
}
}


The method must also be static and contain the this keyword before the type.

3. Now in order to use this extension, we could code something like the following:

int? i = null;
if (i.IsNullOrZero())
Console.WriteLine("i is null");


The above code is alot cleaner than testing for zeros and nulls. Of course you could let your imagine run wild with extension methods. But I recommend only using them for simple operations as your code could soon become too complicated which would then become more difficult to maintain especially when new developers come on board.

0 comments: