var dict = new Dictionary<string, object>();
DateTime? myDate;
/*Next line gives: Type of conditional expression cannot be
determined because there is no implicit conversion between 'System.DateTime?'
and 'System.DBNull' */
dict.Add("breakit", myDate.HasValue ? myDate.Value : DBNull.Value);
I don't understand why there needs to be an implicit conversion if one or the other is going into a dictionary expecting type Object.
Except in very simple cases, you should discourage the use of nested ternary operators. It makes the code harder to read because, indirectly, your eyes scan the code vertically.
In the above syntax, we have tested 2 conditions in a single statement using the ternary operator. In the syntax, if condition1 is incorrect then Expression3 will be executed else if condition1 is correct then the output depends on the condition2.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
You can't Nest a ternary block and still execute multiple actions within it.
In C#, every conditional expression must have a type. What type is your expression of?
I understand your concern, the conversion is not needed for your particular case, but this is how C# compiler works, so you have to obey its rules.
This should work instead (I didn't check though):
dict.Add("breakit", myDate.HasValue ? (object)myDate.Value : (object)DBNull.Value);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With