Wednesday, July 14, 2010

Fun with Extension Methods

In a Pair-programming session Fhad showed me some interesting ideas for extension methods.
He and his colleague used extension methods to get rid of those nasty null checking stuff:

if (object != null)
    return object.SomeProperty;
    return string.Empty;

They use a generic extension method together with a lambda expression:

public static TResult IfNotNull(this T obj, Func func, TResult value) where T : class
    return obj == null ? value : func(obj);

Here is an example on how to use this extension method:

SomeClass myClass;
string value = myClass.IfNotNull(obj => obj.SomeProperty, string.Empty);
//value contains string.Empty

myClass == new SomeClass();
myClass.SomeProperty = “something”;
value = myClass.IfNotNull(obj => obj.SomeProperty, string.Empty);
//value is now “something”

And here are some more extension methods I'm using:

public static bool HasItems(this IList list)
    return list.Count > 0;

public static bool IsEmpty(this IList list)
    return list.Count == 0;

Example on how to use them:

List _stringList = new List;

if (_stringList.HasItems()) ...
if (_stringList.IsEmpty())...

I think this code is much easier to read.

Finally a link to the msdn website about Extension Methods:

and about Lambda Expressions: