Snack size C#: null coalescing operator
You need to assign the value of an expression to a variable, unless that expression evaluates to null, in which case default to something else. And if that something else is also null, then fall back to another value, and so on.
For example, a web page that uses a theme setting to control look-and-feel. If the user has selected their own theme then use that; otherwise use the site’s default theme; or, if that’s not defined, use the global theme; or finally if no global theme is defined then fall back to a system default.
The long, readable version
Using good, old fashioned, conditional logic.
string theme;
if (userTheme != null)
{
theme = userTheme;
}
else if (siteTheme != null)
{
theme = siteTheme;
}
else if (globalTheme != null)
{
theme = globalTheme;
}
else
{
theme = defaultTheme;
}
The shorter, slightly befuddling version
By nesting the ternary conditional operator in a most disagreeable way.
string theme =
userTheme != null ? userTheme
: siteTheme != null ? siteTheme
: globalTheme != null ? globalTheme
: defaultTheme;
The deluxe C# 3.0 version
With the overkill of an implicitly-typed array, an IEnumerable extension method, and a lambda predicate.
string theme = new [] {
userTheme, siteTheme, globalTheme, defaultTheme
}.First(t => t != null);
The elegant coalescence version
With C# 2.0’s null-coalescing operator, doing what it does best.
string theme = userTheme ?? siteTheme ?? globalTheme ?? defaultTheme;