This code:
var userType = viewModel.UserType == UserType.Sales
? new Sales()
: new Manager();
Gives me this compiler error message:
Type of conditional expression cannot be determined because there is no implicit conversion between 'Models.Sales' and 'Models.Manager'.
Why can I not initialize a var depending on the outcome of a condition? Or am I doing something wrong here?
EDIT: @Tim Schmelter, I didn't saw that post, all I could find were int and null, bool and null:
Type of conditional expression cannot be determined because there is no implicit conversion between 'string' and 'System.DBNull'
Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and <null>
Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '<null>'
But no custom types.
You need to cast the first possibility to a common base type or interface, e.g.:
var userType = viewModel.UserType == UserType.Sales
? (IUser)new Sales()
: new Manager();
Otherwise the compiler does not know what type it should create and will use Sales and so it would fail when trying to assign the Manager instance.
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