Coalescing object and accessing it
I was reading Twitter yesterday and spotted a tweet from Shawn Wildermuth about his pain about using coalesce operator (??
) in C# and doing immediately something with result.
I had same problem maybe a year back, when I was dealing heavily with XML and LINQ to XML (but it doesn’t matter). I created for myself a little extension method to help me solve writing lines like:
Something x = (a == null ? "FooBar" : a.FooBar);
The method:
public static TResult ObjectCoalesce<T, TResult>(this T o, Func<T, TResult> operation, TResult @default)
where T : class
{
if (o == null)
return @default;
else
return operation(o);
}
And simple usage:
Something x = a.ObjectCoalesce(y => y.FooBar, "FooBar");
When it’s nested in some calls, it really helped me to make my code shorter. You can also play (I did) with idea of having the default parameter as delegate so it will be evaluated only if needed. In some cases it could make a huge difference (i.e. side-effects).