C # initializes var based on ternary state
This code:
var userType = viewModel.UserType == UserType.Sales
? new Sales()
: new Manager();
Gives me this compiler error message:
The type of the conditional expression could not be determined because there is no implicit conversion between "Models.Sales" and "Models.Manager".
Why can't I initialize var depending on the result of the condition? Or am I something wrong here?
EDIT: @Tim Schmelter, I haven't seen this post, all I could find was int
and null
, bool
and null
:
But no custom types.
source to share
You need to pass the first capability to a generic base type or interface, for example:
var userType = viewModel.UserType == UserType.Sales
? (IUser)new Sales()
: new Manager();
Otherwise, the compiler doesn't know what type it should create and will use Sales
, and therefore it will fail when trying to assign an instance Manager
.
source to share
Because :
Any type of expression first_expression and second_expression must be the same, or an implicit conversion must exist from one type to another.
It is not possible in your code to convert from Sales
to Manager
or vice versa. So they are incompatible types, in which case the compiler cannot determine the type. C # is a statically typed language (mostly) and the type of a variable cannot be dynamic unless it is defined as dynamic.
source to share