I hate all of the extra code you have to write to protect your code from Null Reference exceptions, but it's totally necessary at some level. The question is, "How often do you need to write the same code over and over?"
I included this code in a project today (it seemed useful):
internal static class Utility
{
public static TResult SafeGet<T, TResult>(this T instance, Func<T, TResult> nonNullFunction, Func<TResult> nullFunction) where T : class
{
if (instance != null && nonNullFunction != null)
return nonNullFunction(instance);
else if (instance == null && nullFunction != null)
return nullFunction();
// in all other cases, return the default for the type of TResult
return default(TResult);
}
public static TResult SafeGet<T, TResult>(this T instance, Func<T, TResult> nonNullFunction) where T : class
{
if (instance != null && nonNullFunction != null)
return nonNullFunction(instance);
// in all other cases, return the default for the type of TResult
return default(TResult);
}
}
It changes code like this:
int x = (myObjThatMightBeNull != null) ? myObjThatMightBeNull.PropertyINeed : 5; // 5 is default when myObjectThatMightBeNull actuall *IS* null
To code like this:
int x = myObjThatMightBeNull.SafeGet(o => o.PropertyINeed, () => 5); // 5 is default when myObjectThatMightBeNull actuall *IS* null
Or code like this:
int x = myObjThatMightBeNull.SafeGet(o => o.PropertyINeed); // takes default for int (0)
After some discussion with my colleague, Johannes Setiabudi, it was debatable as to the relative value of the new extension method compared to the old technique. I'm still forming my opinion. On the one hand, the "SafeGet" communicates the intent of the code. On the other hand, the lambda syntax may be less understandable to those unfamiliar with it.
Leave your comments if you have ideas that might work or ways to improve the code.