Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic datatypes in object list

Tags:

c#

asp.net

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>

like image 963
Johan Avatar asked Feb 01 '26 20:02

Johan


2 Answers

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);
like image 164
Habib Avatar answered Feb 03 '26 08:02

Habib


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 });
like image 25
Alex Avatar answered Feb 03 '26 10:02

Alex