c# - Conditional Expression Return Type -
i have 2 classes implementing imyinterface
, async method of return type task<imyinterface>
.
why receiving compiler error "there no implicit conversion type" return statement, return somebooleandeterminedbythemethod ? class1 : new class2();
, best procedure resolving this?
full method:
public static async task<imyinterface> mymethodasync(subclass1 class1child) { var listofthings = new list<tuple<int, class1>>(); await task.run(() => { foreach (var item in somecollection) { var dummyclass1 = new class1() {intproperty = 0}; var computationresult = new tuple<int, class1>( dummyclass1.intproperty, dummyclass1); listofthings.add(computationresult); } } try { var returnedclass1 = (from items in listofthings orderby items.item1 select items.item2).firstordefault(); return returnedclass1.booleanproperty ? returnedclass1 : new class2(); } catch ... // not relevant. } class class1 : imyinterface { public int intproperty { get; set;} public bool booleanproperty => intproperty % 2 == 1; // so, in example, booleanproperty return false. } class class2 : imyinterface { // class serves separate class indicate different type used program. } interface imyinterface { }
as documentation ?:
operator explains:
given conditional expression: condition ? first_expression : second_expression;
either type of first_expression , second_expression must same, or implicit conversion must exist 1 type other.
since neither class1 or class2 same type, nor implicit conversion exist between two, can cast either first_expression
or second_expression
interface type, so:
return somebooleandeterminedbythemethod ? (imyinterface)class1 : new class2();
then compiler know expression should evaluate imyinterface
.
Comments
Post a Comment