Can anyone please explain to me what happens behind the scenes when you use ternary operator?
does this line of code:
string str = 1 == 1 ? "abc" : "def";
is generated as a simple if / else statement?
Consider the following:
class A
{
}
class B : A
{
}
class C : A
{
}
Now using ternary expression as follows:
A a1 = 1 == 1 ? new B() : new C();
this doesn’t even compile with this error:
Type of conditional expression cannot be determined because there is no implicit conversion between ‘ConsoleApp1.B’ and ‘ConsoleApp2.C’
Can anyone shed light on this one?
The conditional operator will effectively use the type of the first expression for the second according to whether there is a conversion – and doesn’t take into account bases (otherwise it would just always go to
objectallowing this:? "hello" : 10).In this case, the compiler is correct – there is no conversion between the two types. Add a cast, however on the first one – and it’ll compile –
(A)new B().