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;
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…

5 Replies to “Ternary operators don’t work with nullable value types?”

  1. 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”];

  2. 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!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.