Making use of the ‘??’ operator in C#

The ?? operator was introduced to C# in 2.0 and I made a mental note to myself to use it when possible.

Recently I had to do some tinkering with good ole Request.Form and Request.QueryString and I kept trying get the neurons to connect and figure out the shorter way of doing it. I knew there was another way to do it than write all this.

   1: string filter = Request.QueryString["Filter"];
   2: if (filter == null)
   3: {
   4:     filter = "";
   5: }

And Google is no help when you have no keyword to search. This is when ReSharper came in handy and prompted to replace the above code with this succinct version.

   1: filter = Request.QueryString["Filter"] ?? "";

BTW: If you are coding in VS 2008 check out the ReSharper 4.0 nightly builds, it's awesome.

Written on February 18, 2008