When I first saw the new ?? operator in C# 2.0 I was a bit skeptical. Did we really need another terse operator to further obfuscate our code? Over the last year I've actually found myself using it quite a bit, however, and I think it actually enhances the readability once you get used to it (so I guess the answer was yes, we - or I at least - did :). Take the example of implementing a property that is backed by ViewState in ASP.NET (say for a custom control), a typical implementation might look something like:
public string Title
{
get
{
if (ViewState["title"] == null)
return "Default title";
else
return (string)ViewState["title"];
}
set { ViewState["title"] = value; }
}
Or you could condense things a bit by using the ? operator:
public string Title
{
get
{
return (ViewState["title"] == null) ? "Default title" : (string)ViewState["title"];
}
set { ViewState["title"] = value; }
}
And finally, with the ?? operator you can reduce it even further:
public string Title
{
get { return (string)ViewState["title"] ?? "Default title"; }
set { ViewState["title"] = value; }
}
I use this pattern quite a bit when implementing reference type properties backed by ViewState, and I quite like the way it succinctly expresses the check for null. It's the only one of the three that I feel comfortable leaving the get implementation in one line, so my classes take up less vertical space. YMMV :)
Posted
Dec 07 2005, 08:24 AM
by
fritz-onion