November 14, 2007
@ 10:11 PM

This falls into the "hey, I didn't realize this was available" category. In the 2.0 version of the .NET framework, support was added for nullable types, I'm guessing primarily for improved interaction with databases. Previously, nulls were a real pain to deal with; now they're only a bit more work (the pains not completely gone, but it's not as bad anymore). Lets say you've got a date time field in your database, it can have an actual date filled in or it can be null. In prior versions, you had to rely on "magic" dates to do translations when loading and saving your data (eg. 1/1/1900 is really null). Now you can just define a nullable type by prefixing the type with a question mark ?

 

DateTime? activeStart = (DateTime?)row["ActiveStart"];

 

That's not the point of this post though. They've added a nice operator ?? - so let's suppose I've got a calendar control that returns null if no date has been selected. I'd like to default to the current date if that's the case. I can write code like this:

 

DateTime start = System.DateTime.Now;

if (this.startCalendar.SelectedDate != null)
   start = this.startCalendar.SelectedDate;

 

Or I can use the ?? operator:

 

DateTime start = this.startCalendar.SelectedDate ?? DateTime.Now;

 

That's much simpler code to understand (at least to me). I like this a bit better than the normal ternary "if" support, which I always find a bit difficult to read:

string sample = a==b ? "A=B" : "A<>B" 

Maybe it will grow on me eventually...
 
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: a@href@title, b, i, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview