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.
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! ;-)
This makes use of the construction that each statement has a return value.
int a,b,c;
a=b=c=6;
Now all three value types will be 6 :)
Just excellent c behaviour that we have inherited.
Or like copying stream data into another.
static void Copy(Stream source, Stream destination)
■■■const long Size = 1024;
■■■byte[] buffer = new byte[Size];
■■■long readBytes;
■■■while(0<(readBytes=source.Read(buffer,0,readBytes))
■■■{
■■■■■■destination.Write(buffer,0,readBytes);
■■■}
ps. This code could contain errors as I just typed it in by hand.
Remco, thank you for your objective comment! :D
I'll go contact Blizzard if they can add this most beautifull ?? operator into the World of Warcraft scripting language! That'll be the way to get you over the edge! :D
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