C# Null pass-through extension method

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.

One Response to “C# Null pass-through extension method”

  1. Andy says:

    And what is wrong with:

    int len = (c == null && String.IsNullOrEmpty(c.str)) ? 0 : c.str.Length;

    ?

    It doesn’t look like your code has gotten that much shorter.
    I do understand that lambda syntax looks more elegant than old style. But imho sometimes it just obscures the meaning.

Leave a Reply