qt8gt0bxhw|20009F4EEE83|RyanMain|subtext_Content|Text|0xfbff2e0100000000ac00000001000100
I last posted about the null coalescing operator in .NET 2.0 and just had to post a follow up. I came accross a post on Born 2 Code .NET (via Dennis van der Stelt) where several examples of ?? syntactic sugar are listed to demonstrate how the null coalescing operator surpasses the ternary conditional operator (?:) and if constructs as far as usefulness and readability.
Here's a great sample from the post:
public Brush BackgroundBrush
{
get
{
return _backgroundBrush ??
(
_backgroundBrush = GetBackgroundBrushDefault()
);
}
}
Which translates to (using a traditional if construct)
public Brush BackgroundBrush
{
get
{
if (_backgroundBrush == null)
{
_backgroundBrush = GetBackgroundBrushDefault();
}
return _backgroundBrush;
}
}
The idea here is that the ?? is evaluated first before the return, causing the assignment to occur in the case when the _backgroundBrush variable is null. That is just plain cool. Make sure you check out the link to the post on Born 2 Code .NET for more examples. Also check out Jon Skeet's post on doing elegant comparisons using the null coalescing operator as well.