A Cool Way To Handle ASP.NET Properties Using Nullable Types

Posted by | Filed under , ,

In ASP.NET 1.x, it used to be common to handle the getter of a value type properties thusly:

public int SomeInteger
{
         get
         {
                object val = ViewState["SomeInteger"];
                return val != null ? (int)val : 0;
          }
}

Not bad, but there's more code than needed with nullable types and the "null coalescing operator", anyway. Here's the newer, sleeker way to do the same thing with half the space!

public int SomeInteger
{
         get{ return ViewState["SomeInteger"] as int? ?? 0; }
}

So what's going on in this snippet? Well, we cast the value to a nullable int (int?) which holds a reference to either an int or null then we use the aforementioned ?? operator to return our default value or 0 in the case of null

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

Add comment


 

  Country flag

biuquote
  • Comment
  • Preview
Loading