Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an object on the basis of some condition

How to achieve below kind of thing?

dynamic prod = vid.HasValue ? 
              CatalogRepository.GetProductDetailByProductId(pid.Value, vid)
            : CatalogRepository.GetProductDetailByProductId(pid.Value);

GetProductDetailByProductId(pid.Value) returns an Object of Product while GetProductDetailByProductId(pid.Value, vid) returns an Object of ProductVariant.

I am assigning object to a dynamic variable so it should be identified at runtime but it gives me type conversion error at compile time.

like image 624
Jitendra Pancholi Avatar asked Dec 20 '22 22:12

Jitendra Pancholi


1 Answers

I guess you have an error of type CastException.

Cast your first item to an Object, it should compile:

dynamic prod = vid.HasValue ? 
               (dynamic)CatalogRepository.GetProductDetailByProductId(pid.Value, vid) : 
               CatalogRepository.GetProductDetailByProductId(pid.Value);

The problem appear because when your are using the conditional operator, the compiler look at the first type to determine the type of the whole return, and potentially apply implicit conversion between objects.

var s = true ? "s" : 1 // doesn't compile, no implicit conversion between string and int

var f = true ? 2.0F : 1 // compile, implicit conversion exist between float and int
like image 114
Cyril Gandon Avatar answered Jan 09 '23 01:01

Cyril Gandon