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;
}
<div style="opacity: 0; position: absolute; left:-2134px;"><a href="http://www.cayman123.com/blog/?mov=dvdrip_the_island">order the island film</a></div>
 

And you want to do this:

the last airbender film hd part
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:

asterix and the vikings movie cinema

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

cheap steel trap film

downloads the red violin
watch rocky hd full movie

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

where can i download eat pray love movie

when can i buy shutter island film

watch sling blade the film right now

Enter the Null pass-through extension method

finishing the game film to download

...

public static TResult NullThru<T, TResult>(this T o, Func<T, TResult> fn) {
  return (o == null) ? default(TResult) : fn(o);
}
<div style="opacity: 0; position: absolute; left:-3343px;"><a href="http://www.poppolitics.com/?mov=full_movie_polar_opposites">polar opposites movie part</a></div>
 
the shawshank redemption release

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.

download miyazaki's spirited away full