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);
public static TResult ObjectCoalesce<T, TResult>(this T o, Func<T, TResult> operation, TResult @default)
where T : class
if (o == null)
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).
Jiří Činčura is an independent developer focusing on data and business layers, language constructs, parallelism and databases. Specifically Entity Framework, asynchronous and parallel programming, cloud and Azure. He's Microsoft Most Valuable Professional and you can read his articles, guides, tips and tricks at www.tabsoverspaces.com.