Archive for the ‘Coding’ Category

C# Null pass-through extension method

Saturday, March 14th, 2009

If you have a class like this:

class C {
  string str;
}

And you want to do this:

C c = ...
int len = c.str.Length;

Then you have to be careful that c is not null and c.str is not null, or exceptions will fly.

So you end up doing this:

C c = ...
int len = (c == null) ? 0 : ((c.str == null) ? 0 : c.str.Length);

Which is ugly and painful if you've got lots of these situations in your code.

Enter the Null pass-through extension method...

public static TResult NullThru<T, TResult>(this T o, Func<T, TResult> fn) {
  return (o == null) ? default(TResult) : fn(o);
}

And suddenly all your troubles are behind you. Simply write this:

C c = ...
int len = c.NullThru(x => x.str.NullThru(y => y.Length));

OK, so it's not the most beautiful code you've ever seen, but it's surely better than the alternative.