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;
else
    return string.Empty;

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

public static TResult IfNotNull<T, TResult>(this T obj, Func<T, TResult> 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<T>(this IList<T> list)
{
    return list.Count > 0;
}

public static bool IsEmpty<T>(this IList<T> list)
{
    return list.Count == 0;
}

Example on how to use them:

List<string> _stringList = new List<string>;

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:
http://msdn.microsoft.com/en-us/library/bb383977.aspx
and about Lambda Expressions:
http://msdn.microsoft.com/en-us/library/bb397687.aspx

Advertisements

One Response to “Fun with Extension Methods”

  1. Today, I stumbled exactly upon these, especially the IfNotNull extension. Whether these extensions are fun or not, some of them make code very hard to read and almost un-debuggable. Personally I really like extenion methods, however one more time I realized that they have to be designed carefully (as everything in software engineering).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: