Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# initialize var depending on ternary condition [duplicate]

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.

like image 752
Quoter Avatar asked Feb 05 '26 00:02

Quoter


1 Answers

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.

like image 58
Christoph Fink Avatar answered Feb 07 '26 13:02

Christoph Fink