Say hello to my little friend - ?? - the Null Coalescing operator

I was recently working on some data access code in ADO.Net (old school, right - I mean who does that anymore?). And I ran into a issue with nullable types. Although nullable types are great, you'd think that they'd make the marshalling of data from application to database easier. But, as I found out it's not as simple as that.

I assumed that I could directly assign an nullable type to an ADO field that supports null. Like so:
row["MyField"] = myNullableDate;
Unfortunately if myNullableDate is null you'll get a runtime exception (not compiletime) stating that you should use DBNull instead. Ugh!

So you end up writing this:
if (myDate == null)
{
    row["MyField"] = DBNull.Value;
}
else
{
    row["MyField"] = myDate;
}
Which works but that's a lot of code just to assign to an ADO field - particularly if you've got a lot of fields to populate.

Enter my new best friend the Null Coalescing operator - ??

OK, so it looks a little arcane - you either know what it means or you don't. But hey, if you've chosen to use C# you should be happy to embrace its syntax - love the skin you're in, you know?

What you end up with is this:
row["MyField"] = myNullableDate ?? (object)DBNull.Value;
Yes, it's a little obscure - but it's very neat! And we're back to a single line for assignment. In my example there's a slight quirk in that you have to cast DBNull to an object because ?? requires its alternative values to be of the same type.

I'm not zealous about this - use it or not - it's up to you. If you want to write a full if/else statement, fine. But I thought I'd highlight an elegant bit of C# goodness that you may not have seen.

Check out ScottGu's great demonstration of using ?? with LINQ.

Comments