Using the ?? operator for ViewState properties

Onion Blog

Syndication

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
Filed under:

Comments

Andrew Robinson wrote re: Using the ?? operator for ViewState properties
on 12-07-2005 7:32 AM
Fritz,

Why not use the same patter with value types? You need to cast to a nullable type but I like the way it looks and works:

public int TitleID
{
get { return (int?)ViewState["titleID"] ?? -1; }
set { ViewState["titleID"] = value; }
}
Fritz Onion wrote re: Using the ?? operator for ViewState properties
on 12-07-2005 7:42 AM
I knew someone was going to pick up on that :) I actually meant to remove that reference to only using it for reference types, because I actually do use it for value types as well (I was initially hesitant for fear of additional boxing, but it's in ViewState already as an object reference, so there's nothing youc an do).
However, there's no need to use a nullable type here, since it will never return null if you write it correctly:

public int TitleID
{
get { return (int)(ViewState["titleID"] ?? -1); }
set { ViewState["titleID"] = value; }
}
}
Andrew Robinson wrote re: Using the ?? operator for ViewState properties
on 12-07-2005 8:20 AM
Thanks,

I wasn't wrapping the ViewState in parens (). So the coalescing operator was being applied to my already cast value. Now I have learnt something. Will have to slightly change my pattern. Thanks. Wasn't trying to nitpick.

Any news up an updated book? Your 1.0 book is one of my favorites.

-Andrew
Fritz Onion wrote re: Using the ?? operator for ViewState properties
on 12-07-2005 8:30 AM
Oh it wasn't nitpicking, it was a good point - thanks for bringing it up.
And the 2.0 edition of my book should be out in the spring of 2006.

Cheers,
Fritz
John Lam wrote re: Using the ?? operator for ViewState properties
on 12-07-2005 9:01 AM
I use ||= (the Ruby equivalent) all the time. The point is that it's idiomatic as opposed to intuitive (much like the ternary operator). So people familiar with the idiom will instantly recognize what it is, and people unfamiliar with the idiom will be prompted to look it up :)
Sean Chase wrote re: Using the ?? operator for ViewState properties
on 12-07-2005 1:34 PM
I just blogged about this the other day and did the same thing Andrew did using a (bool?) cast. This...

(int)(ViewState["titleID"] ?? -1

...is what I want. :-)

Also, +1 on your book Fritz.
どっとねっとふぁんBlog wrote ??オペレータのちょっと便利な使い方
on 12-07-2005 7:54 PM
Using the ?? operator for ViewState properties
ASP.NET????????????????????????????????
 
Wouter van Vugt wrote re: Using the ?? operator for ViewState properties
on 12-08-2005 2:33 AM
Isn't there anyone who thinks altering a programming language for some silly product (or less silly in this case) which has been, is a very very very bad idea?
Fritz Onion wrote re: Using the ?? operator for ViewState properties
on 12-08-2005 5:40 AM
I'm not sure why you think the ?? operator is a modification targeted at a product. It's a general language feature for dealing with null return values.
Christopher Steen wrote Link Listing - December 8, 2005 (Part II)
on 12-08-2005 6:50 PM

Application Configuration with Libraries [Via: CNagel ]
Automatic reporting of client-side script...
TheChaseMan's Frenetic SoapBox wrote Correction...errrrr, improvement maybe?
on 12-08-2005 7:01 PM
Joel Ross wrote ??: The New C# Operator
on 12-09-2005 5:10 PM
TrackBack wrote RossCode.com - ??: The New C# Operator
on 12-09-2005 5:10 PM
RossCode.com - ??: The New C# Operator
David Taylor wrote re: Using the ?? operator for ViewState properties
on 12-12-2005 2:43 AM
Yes, I have liked the ?? operator for a long time. Particularly for subset of cases where you might currently be using the ? operator, and can write it much more succinctly with the ?? operator.

Of course...I hate the actual name of the ?? operator which I will not repeat for fear of doubling the length of my blog entry ;-)
on 12-15-2005 9:41 AM
Z nowosci w C# 2.0

Przyklad uzycia ?? (za blogiem Onion Blog)
Zupancic Perspective wrote New Operator in C# 2.0: ?? (null coalescing operator)
on 01-02-2006 1:42 AM
Greg McKinley.com wrote Nullable Value Types and the C# Null-Coalescing Operator (??)
on 09-29-2006 2:37 PM
Just a couple of links to some useful 2.0 functionality




Eric Gunnerson - Nullable Types in...
Vin klassen wrote re: Using the ?? operator for ViewState properties
on 08-13-2007 11:30 PM
It could have been a good thing if the ?? operator worked with dbnull values returned from a database. These values are ussually checked prior to assigning to some variable

For example
If only i could do this

BookID = (int?)dRow["bookid"] ?? null;

instead of this

if (dRow["bookid"] != DBNull.Value)
{ BookID = (int?)dRow["bookid"]; }
else
{ BookID = null; }

I 'll put it on my next wishlist
Zolpidem and sleepwalking. wrote Cheap zolpidem.
on 08-14-2008 4:27 PM

Zolpidem overdose. Zolpidem.

ASP.NET MVC Archived Blog Posts, Page 1 wrote ASP.NET MVC Archived Blog Posts, Page 1
on 10-03-2008 6:34 PM

Pingback from  ASP.NET MVC Archived Blog Posts, Page 1

Add a Comment

(required)  
(optional)
(required)  
Remember Me?