The ?? Operator
The Problem
Database access has to be my least favorite activity to code, right up there with coding public data access (to private fields). The worst thing about coding database access is â easily â the need to check for null values. I recently found a nugget in .NET that makes the process a bit less painless, and Iâm putting it out here in the hopes that it will help somebody avoid this:
public void Read(){// â¦System.Data.SqlClient.SqlDataReader rdr = new System.Data.SqlClient.SqlDataReader();if (!rdr.IsDBNull(0)){// Yay! Itâs not null.}if (!rdr.IsDBNull(1)){// Wow, the second field is not null either.}if (!rdr.IsDBNull(3)){// And neither is this one; Iâm so excited.}if (!rdr.IsDBNull(4)){// This one isnât either? Really?}// â¦if (!rdr.IsDBNull(723498234)){// And this oneâs not null either. Oh, what joy.}}
The Solution
Enter ??. Wait, what? ?? is an actual operator in C# and not a spelling mistake on your part? Iâve never heard of it in my entire life (okay, so maybe you did hear of it before, but I havenât, not âtil yesterday!).
Youâd code the ?? like this:
AwesomeObject someAwesomeObject = new AwesomeObject();someAwesomeObject.AwesomeField = rdr.GetString(10) ?? string.Empty;
To read more on the ?? operator, try this MSDN article.
I finally found out that the operator is called null coalescing operator and is available in C# 2005 only. Another reason C# rocks. ; -) Any questions?