Johan
Johan

Reputation: 35193

Dynamic datatypes in object list

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>

Upvotes: 3

Views: 101

Answers (3)

Alex
Alex

Reputation: 8937

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 });

Upvotes: 2

Habib
Habib

Reputation: 223287

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);

Upvotes: 3

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98760

From ?: Operator

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.

As the error says, there is no implicit conversion between long and List<long>. long is an integer type and List<long> is a generic type.

As an alternative, you can use explicit conversation with both of them to object like:

(object)foo : (object)bar

Upvotes: 0

Related Questions