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

:

The type of the conditional expression cannot be determined because there is no implicit conversion between 'string' and 'System.DBNull'

The type of the conditional expression cannot be determined because there is no implicit conversion between 'int' and <null>

The type of the conditional expression cannot be determined because there is no implicit conversion between 'int' and '<null>'

But no custom types.

+3


source to share


3 answers


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

.

+3


source


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.

+2


source


You need to explicitly declare userType

as a normal type Sales

and Manager

. For example, if they both come from User

, then do the following:

User userType = viewModel.UserType == UserType.Sales 
                    ? new Sales() 
                    : new Manager();

      

+1


source







All Articles