Reputation: 329
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();
}
Upvotes: 1
Views: 27176
Reputation: 172398
You may simply try this:
i = isOn? 10:20
The MSDN says:
The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, second_expression is evaluated and becomes the result. Only one of the two expressions is evaluated.
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:
i = isOn ? foo() : bar(); //assuming both methods return int
Upvotes: 5
Reputation: 6374
Please try the following. BTW, it only works for value assignments not method calls.
i = isOn ? 10 : 20;
Reference:
Upvotes: 14
Reputation: 4395
You're on the right track but a little off.
i = isOn ? 10 : 20;
Here 10
will be assigned to i
if isOn == true
and 20
will be assigned to i
if isOn == false
Upvotes: 4
Reputation: 2714
Here's an explanation that might help. The statement you're looking for is:
i = isOn ? 10 : 20;
And here's what that means:
(result) = (test) ? (value if test is true) : (value if test is false);
Upvotes: 3