Sunday, 15 July 2012

C# initialize var depending on ternary condition -



C# initialize var depending on ternary condition -

this question has reply here:

implicit conversion issue in ternary status [duplicate] 4 answers

this code:

var usertype = viewmodel.usertype == usertype.sales ? new sales() : new manager();

gives me compiler error message:

type of conditional look cannot determined because there no implicit conversion between 'models.sales' , 'models.manager'.

why can not initialize var depending on outcome of condition? or doing wrong here?

edit: @tim schmelter, didn't saw post, find int , null, bool , null:

type of conditional look cannot determined because there no implicit conversion between 'string' , 'system.dbnull'

type of conditional look cannot determined because there no implicit conversion between 'int' , <null>

type of conditional look cannot determined because there no implicit conversion between 'int' , '<null>'

but no custom types.

you need cast first possibility mutual base of operations type or interface, e.g.:

var usertype = viewmodel.usertype == usertype.sales ? (iuser)new sales() : new manager();

otherwise compiler not know type should create , utilize sales , fail when trying assign manager instance.

c# ternary-operator

No comments:

Post a Comment