If I am to write this piece of code, it works fine with the normal 'if-else' layout.
if(isOn)
{
i = 10;
}
else
{
i = 20;
}
Although I am unsure how to convert this using the ternary operator
isOn = true ? i = 1 : i = 0;
Error: Type of conditional expression cannot be determined because there is no implicitly conversion between 'void' and 'void'.
EDIT:
Answer = i = isOn ? 10 : 20;
Is it possible to do this with methods?
if(isOn)
{
foo();
}
else
{
bar();
}
Please try the following. BTW, it only works for value assignments not method calls.
Reference:
You're on the right track but a little off.
i = isOn ? 10 : 20;
Here
10
will be assigned toi
ifisOn == true
and20
will be assigned toi
ifisOn == false
Try the following:
try the following
You may simply try this:
The MSDN says:
EDIT:-
If you want to invoke
void
methods in a conditional operator, you can use delegates else it is not possible to use ternary operators for methods.And if your methods are returning something then try like this:
You need:
where
true
is your condition.