Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 conditional 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?

like image 936
Maxim Gershkovich Avatar asked Nov 28 '25 21:11

Maxim Gershkovich


1 Answers

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.

like image 133
Jon Avatar answered Dec 01 '25 12:12

Jon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!