NullsafeGet extension method? Simplicity for the cost of readability??
2 min read
2 min read
class PersonNow consider the case where you'd like to access the Street property of the Address object
{
public string Name { get; set; }
public Address Address { get; set; }
}
class Address
{
public string Street { get; set; }
public string GetCountry()
{
return "Italy"; //just dummy code
}
}
//some code, person is an instance of PersonI guess everyone agrees that this will give a nice NullReferenceException if the Address object is null. This results in continuously (now this is just a dummy example) checking for null
textBoxStreet.Text = person.Address.Street;
...In this example it even looks simple enough, but in certain conditions it may be quite awkward. I actually found the approach on a Stackoverflow post which pointed to this blog here. A solution is to use extension methods which - apparently - can also be applied to a null instance of an object.
if(person.Address != null)
textBoxStreet.Text = person.Address.Street;
public static class NullSafeGetExtensionI called it "NullsafeGet", another commonly used name is "IfNotNull"...it's just a matter of preferences. This solution allows to write the above code like
{
public static U NullsafeGet<T, U>(this T t, Func<T, U> fn)
{
if (t != null)
return fn(t);
else
return default(U);
}
}
//some code, person is an instance of PersonThis turns out to be a quite nice solution since you don't need all of the nested ifs. In this example it was obviously simple enough to write the if instead of using the extension methods. This piece from the Stackoverflow post probably illustrates the advantage in a more clear way:
textBoxStreet.Text = person.NullsafeGet(x => x.Address).NullsafeGet(x => x.Street);
string activeControlName = null;And with the extension method solution...
var activeForm = Form.ActiveForm;
if (activeForm != null)
{
var activeControl = activeForm.ActiveControl;
if(activeControl != null)
{
activeControlname = activeControl.Name;
}
}
activeControlname = activeForm.NullsafeGet(x => x.ActiveControl).NullsafeGet(x => x.Name);Although this looks quite nicely, my doubt is on the readability of the code itself....So I don't know whether I'll really use it...