Conditional operator in C# and return types [duplicate]
Possible Duplicates:
Why does null need an explicit type cast here? Nullable types and the ternary operator. Why won't this work?
Attempting to do the following:
sqlCmd.Parameters.Add("@DateCreated", System.Data.SqlDbType.DateTime).Value
= myObject.DateCreated == DateTime.MinValue
? DBNull.Value : myObject.DateCreated;
I am getting this error:
Type of conditio开发者_运维技巧nal expression cannot be determined because there is no implicit conversion between 'System.DBNull' and 'System.DateTime'
I obviously understand the error but why does type even matter given that Parameters.Value is of type object? Is there a way to accomplish what I am trying to do?
It doesn't make a difference that the return value is going into something that is an object
, because the type of the return value has to be determined first.
Cast one of the two values (DBNull.Value
, myObject.DateCreated
) to a base of the other and you 'll be fine. In this case, the base can even be object
.
精彩评论