Advanced usage of the ?? operator

P.J. van de Sande from the (Dutch) weblog Born 2 Code .NET has two posts about the in .NET 2.0 new ?? operator. In the first post he explains what it does and why he likes it. After some comments, he decided to write another post about it, trying to explain even further why he likes it so much. But now he pulls some code from his sleeve I really had to take a good look at.

public Brush BackgroundBrush {   get   {     return _backgroundBrush ??     (         _backgroundBrush = GetBackgroundBrushDefault()     );   } }

You have to know how this is evaluated to understand it. Before it returns anything, it first evaluates the ?? operator, which is probably understood much better by the following code block.

public Brush BackgroundBrush {   get   {     if (_backgroundBrush == null)     {       _backgroundBrush = GetBackgroundBrushDefault();     }     return _backgroundBrush;   } }

But still, it’s some lovely code. You decide for yourself if you want to see code like that in your project. Perhaps Jan Schreuder would be more happy to see code like this instead of the code in his latest post! 😉