List<object> list = new List<object>();
long foo = 1;
List<long> bar = new List<long>(){ 1,2,3 };
bool someBool = false;
list.Add(new { someProp = someBool ? foo : bar });
Why can't someProp datatype act dynamic? The datatype isn't specified as the object key so I don't see the problem.
There is no implicit conversion between long and
List<long>
The error is because of the conditional operator(also known as ternary operator) ?. It is suppose to return a single type of object, since long and List<long> are different. You are getting the error.
Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.
A simplest and more readable alternative (IMO) would be:
if (someProp == someBool)
list.Add(new { someProp = foo });
else
list.Add(new { someProp = bar });
But the above two would be different Anonymous type objects.
Or you can get rid of Anonymous object and simply add the two to list, since it is List<object> like:
if (someProp == someBool)
list.Add(foo);
else
list.Add(bar);
The ? operator requiers to have the same type for your expressions. You can cast your foo and bar to object type manually (explicitly) to the same type, like this:
list.Add(new { someProp = someBool ? (object)foo : bar });
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