Monday, January 26, 2009

Neat way to handle Nullable types ...

Ever since I read Rick Strahl's blog post on the C# ?? operator, I've been in love with the C# ?? operator. Mostly I use it as a clean way to test a ViewState variable for null in a property. For example,

protected string stringToPersistOnPostBack {
   get {
      return (ViewState[this.ClientID + "_stringToPersistOnPostBack"] ?? "").ToString();

Somewhere along the way, the real purpose of the ?? operator was forgotten though. It's true purpose is to give a default value to a Nullable type thus allowing you to use it as the type.

I started with this code:

bool doExpand = (IsPostBack && e.Node.Expanded);

which gave me an error: "Operator && cannot be applied to types 'bool' and 'bool?'"

While I often enjoy the use of Nullable types, they do introduce often annoying, sometimes unnecessary complexity to code. But thankfully, the nice folks at Microsoft came up with a rather nifty solution ... the ?? operator.

At first, I thought I'd have to use the ?? operator to give e.Node.Expanded a default value of false AND cast the object to bool. Instead, all I had to do was this:

bool doExpand = (IsPostBack && (e.Node.Expanded ?? false));

See? Neat!

No comments: