I just coded a little application and very often I was having to check to see if the object was null before attempting to access one of its properties.  If it was null, I would use an arbitrary default value.  This ultimately was to prevent the dreaded NullReferenceException.

string output;
if (myObj == null) {
    output = "Unknown";
}
else {
    output = myObj.Name;
}

This bit of code was repeated over and over again making my method very long. Bad. And it looked very messy so I made a little helper method:

public static TReturn GetValueOrDefault<TReturn>(object obj, TReturn defaultValue, Func<TReturn> expression) {
    return obj == null ? defaultValue : expression();
}

This also uses the lovely TReturn so you it can handle any type.

Using this helper method is very simple:

return GetValueOrDefault(myObj, "Unknown", () => myObj.Name);

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 
© 2011 athe.la blog Suffusion theme by Sayontan Sinha