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.
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
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