c# - Unexpected behaviour in ternary operator -
i came across weird behavior when changed if-else ternary operator return statement.
i've simplified code here:
class foo { private bool condition; private int intvalue = 1; private decimal decimalvalue = 1m; public object ternaryget { { return condition ? decimalvalue : intvalue; } } public object ifelseget { { if (condition) return decimalvalue; return intvalue; } } public foo(bool condition) { this.condition = condition; } } class program { static void main(string[] args) { var footrue = new foo(true); var foofalse = new foo(false); console.writeline("{0}, {1}", footrue.ternaryget.gettype(), footrue.ifelseget.gettype()); console.writeline("{0}, {1}", foofalse.ternaryget.gettype(), foofalse.ifelseget.gettype()); } }
the output is:
system.decimal, system.decimal system.decimal, system.int32
i'd expect second row output int32 on both getters, ternary i'm getting incorrect clr type int.
never mind code , it's trying - i'm curious why happening, if can explain it, i'd appreciate it.
result of ternary (conditional) operator of single type - one/both of options casted common type:
var result = condition ? decimalvalue : intvalue;
type of result
must known statically @ compile time. since there cast int
decimal
decimal
type selected type of whole ? :
operator.
so whole function can written (showing automatic casts):
public object turnaryget { { /*decimal*/ var result = condition ? decimalvalue : (decimal)intvalue; return (object)result; } }
Comments
Post a Comment