Reputation: 723
I am posting this question because I found nothing similar regarding this type of post. I am learning ternary operators. I want to perform action like shown below:
bool Divisible = false;
foreach (var Number in NumberList))
{
var Number = 242;
if ((Number %= 2) | (Number %= 6))
{
Divisible = true;
}
else
{
Divisible = false;
}
}
We can write this using the ternary operator like this:
var Divisible = (Number %= 2 | Number %= 6) ? false : true ;
But if in else block there are multiple statements then what to do?
bool Divisible = false;
foreach (var Number in NumberList))
{
var Number = 242;
if ((Number %= 2) | (Number %= 6))
{
Divisible = true;
}
else
{
Divisible = false;
break;
}
}
How can we write ternary operator with multiple else statements? Please share your knowledge of ternary operators.
Upvotes: 5
Views: 3784
Reputation: 8798
It's a arguably a shockingly bad idea but you could call methods in the ternary operators that return the type the assignment is looking for. eg
string doNotDoThis = yeahNah ? iToldYou(bad) : notToDoThis(idea);
// ...
string iToldYou(object thing)
{
// you can do stuff here with thing but seriously?
return "yeahNah was yeah";
}
string notToDoThis(object thing)
{
// you can do stuff here with thing but seriously?
return "yeahNah was nah";
}
Upvotes: 1
Reputation: 723638
But if in else block there are multiple statements then what to do?
If the statements are unrelated, then you don't use the conditional operator. Just use an if-else like you already have.
In your case, since your code needs to break if and only if Divisible
is set to false, then you cannot use a conditional operator even if you wanted to hack it in, because a break is a statement, not an expression, and therefore cannot appear as part of a conditional operator.
In general, you only use the conditional operator when you want to decide between assigning one of two values based on a condition. For anything else, you should really be using a regular if-else construct. Don't try to shoehorn the conditional operator into just about any decision-making code because you'll more often than not find yourself running into problems such as this one.
Upvotes: 5
Reputation: 4470
The ternary operator (that "shorthand if-else") is only intended to evaluate one of two statements based on the boolean. It's not so much a flow-control construct like if; it actually returns the result of the statement it executes. You can't use it to execute code like that.
You can read more on how the ternary operator works here ?: Operator (C# Reference)
Also for your original code you can just do the following :
var Divisible = !(Number %= 2 | Number %= 6)
Upvotes: 1