Reputation: 3
I've been through the various answers here with this one already, but none give an answer that actually works. The core issue (obviously) is that DateTime hasn't any concept of NULL, so the usual
string dateValue = myReader.IsDBNull (4) ? null : myReader.GetDateTime(4) ;
doesn't work.
I've tried
DateTime? nextDue = myReader.GetDateTime(3) == DBNull.Value ? null : (DateTime?)myReader.GetDateTime (3) ;
but that gives
Operator '==' cannot be applied to operands of type 'System.DateTime' and 'System.DBNull'
Changing to
DateTime? nextDue = myReader.GetDateTime(3) = DBNull.Value ? null : (DateTime?)myReader.GetDateTime (3) ;
produces
Cannot implicitly convert type 'System.DBNull' to 'bool'
I ended up changing the SQL to not output NULL values, but I'd still like to crack this one, as it will be useful elsewhere
Upvotes: 0
Views: 296
Reputation: 13351
try
DateTime? nextDue = myReader.GetValue(3) == DBNull.Value ? null : (DateTime?)myReader.GetDateTime (3);
Upvotes: 0
Reputation: 4803
Firstly Your syntax here:
DateTime? nextDue = myReader.GetDateTime(3) = DBNull.Value ? null : (DateTime?)myReader.GetDateTime (3) ;
id wrong. Should be:
DateTime? nextDue = myReader.GetDateTime(3) == DBNull.Value ? null : (DateTime?)myReader.GetDateTime (3) ;
Secondly you could use:
DateTime? nextDue = myReader.IsDBNull(3) ? null : (DateTime?)myReader.GetDateTime (3) ;
Upvotes: 1
Reputation: 13975
You could try
DateTime? nextDue = myReader.IsDbNull(3) ? null : (DateTime?) myReader.GetDateTime (3)
Upvotes: 1
Reputation: 27103
You need to cast the null
to DateTime?
:
DateTime? nextDue = myReader.IsDBNull(3) ?
null as DateTime? :
(DateTime?)myReader.GetDateTime (3)
Upvotes: 0
Reputation: 7747
Just use:
DateTime? nextDue;
if (myReader.GetDateTime(3) == DBNull.Value)
nextDue = myReader.GetDateTime(3);
else
nextDue = null;
Alternatively:
DateTime? nextDue;
if (myReader.IsDBNull(3))
nextDue = myReader.GetDateTime(3);
else
nextDue = null;
Upvotes: 0