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:

  1. public void Read()
  2. {
  3. // …
  4.  
  5. System.Data.SqlClient.SqlDataReader rdr = new System.Data.SqlClient.SqlDataReader();
  6.  
  7. if (!rdr.IsDBNull(0))
  8. {
  9. // Yay! It’s not null.
  10. }
  11.  
  12. if (!rdr.IsDBNull(1))
  13. {
  14. // Wow, the second field is not null either.
  15. }
  16.  
  17. if (!rdr.IsDBNull(3))
  18. {
  19. // And neither is this one; I’m so excited.
  20. }
  21.  
  22. if (!rdr.IsDBNull(4))
  23. {
  24. // This one isn’t either? Really?
  25. }
  26.  
  27. // …
  28.  
  29. if (!rdr.IsDBNull(723498234))
  30. {
  31. // And this one’s not null either. Oh, what joy.
  32. }
  33. }

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:

  1. AwesomeObject someAwesomeObject = new AwesomeObject();
  2.  
  3. 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?