Ternary operators don’t work with nullable value types?
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…
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”];
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!
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!
The new features of .NET nullable value type is great.
Using a question mark (?) after the type or using the generic style Nullable.
Nullable nullDateTime;
or
DateTime? nullDateTime = null;
Full Source..Nullable DateTime
Crony