I’ve got the following situation:
DateTime? myDt = (DateTime) row["Column"];
This fails when retrieving a DBNull value, so we check for that:
DateTime? myDT = (row["Column"] == DBNull.Value) ? null : (DateTime) row["Column"];
This won’t compile, however doing:
DateTime? myDT;
if(row["Column"] == DBNull.Value)
myDT = null;
else
myDT = row["Column"];
works fine, now, I realise I can simplify that statement, but, for the purposes of this post, it is a closer match to the ternary operator.
Why won’t the ternary op work with the value type? It works perfectly with a string…
4 responses so far ↓
Ron Ward // 2008, June, 4 at 20:59 |
Just figured this out myself:
You need to cast both of the possible return values to your nullable type, ie:
DateTime? myDT = (row["Column"] == DBNull.Value) ? (DateTime?) null : (DateTime?) row["Column"];
cskardon // 2008, June, 5 at 7:12 |
Ahh, I see, I guess it’s being used to the implicit nature of most of C#…
I still wouldn’t expect to have to cast my results to the nullable types. It seems to go against how the rest work.
Alas, nice work though!
Robin // 2008, July, 17 at 15:00 |
I’m not gonna take credit for this, but take a look at this!!!::
http://devlicio.us/blogs/alan_northam/archive/2008/03/06/ado-net-nullable-types-casting-dbnull-and-you.aspx
DateTime? myDt = row["Column"] as DateTime?;
The cast above is actually failing but casting with “as” doesn’t throw an exception and returns a null value which is just what we want.
Spread the word!
adeel // 2008, October, 27 at 4:46 |
The new features of .NET nullable value type is great.