Thursday, September 28, 2006

Some of the cool new features of the C# 2.0 language are the ?? operator and nullable types.

?? returns the left operand if not null and the right otherwise. For example:

string name = null;
Debug.WriteLine( "Hello " +
          name ?? "George"
);


...results in the output:

"Hello George"


...because the string variable "name" is null.

Nullable types, on the other hand, allow a struct (which includes built-in types like int and double) to have a null value. This comes in handy when you want to designate a default uninitialized value for a type. For instance, whereas before a developer might have used a convention where -1 or Int32.MinimumValue stood for "uninitialized", now you can just have null (which makes a lot more sense)!

Nullable types are denoted by a question mark following the type name. For instance:

double? d = 1.2;
//legal because this is a nullable type!
d = null;


Both of these new features are powerful enough alone, but in combination, they yield a neat new readable timesaver for things like ASP.NET server control properties!

Ever see a construct like this?

public int Count
{
     get
     {
           object count = ViewState["Count"];
           return ( count != null ? (int)count : 0 );
      }
      set{ ViewState["Count"] = value; }
}



This was a common way to communicate stored property values from ViewState with ASP.NET 1.x, but with C# 2.0 and the new language enhancements I described, we can shorten the above to this:

public int Count
{
      get{ return ViewState["Count"] as int? ?? 0; }
      set{ ViewState["Count"] = value; }
}


Cool, huh?

Labels: ,

0 Comments:

Post a Comment

<< Home