Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use a ternary operator with this expression? [duplicate]

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.

like image 849
scottm Avatar asked Jun 28 '11 14:06

scottm


People also ask

Why ternary operator should not be used?

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.

Can ternary operator have two conditions?

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.

What are the three conditions in a ternary operator?

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.

Can ternary operators contain multiple actions?

You can't Nest a ternary block and still execute multiple actions within it.


1 Answers

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);
like image 163
Zruty Avatar answered Dec 02 '22 22:12

Zruty