Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Is there a way for me to have two results
for a ternary Operator for Example

string mystring = (textbox1.Text == "")? "X" some bool == true :"O";
help please ???
two results "X" and Somebool being the results
Posted
Comments
Sriram Chitturi 27-Mar-12 19:12pm    
Please write your requirement in plain englishn for us to attemp to write in .NET.

No. This is equivalent to if-else operator with exactly two alternatives. You always return one result or another, never both.

—SA
 
Share this answer
 
You can test 2 conditions and have 2 possible results with that:

C#
string mystring = textbox1.Text == "" && some_bool == true ? "X" : "O";


In that case mystring will be "X" if both conditions are met and "0" otherwise (1 or no condition met)

Or you can do 2 test and have 3 results like this:
C#
string mystring = textbox1.Text == "" ? "X" : some_bool ? "*" : "0";


In that case mystring will be "X" if the string is empty. Otherwise, it will be "*" if some_bool is true and "O" if not.

EDIT:

In C++, it would be possible to set 2 values using comma operator but this is not valid in C#. Anyway, such construct are not recommended as it make the code less maintainable.
C++
// Only in C++
bool some_bool = false;
String ^mystring = textbox1.Text == String::Empty ? (some_bool = true, "X") : "O";


If the string is empty, then both mystring and some_bool would get updated. This does not compile in C# (even after removing the ^).


Your question is not clear...
 
Share this answer
 
v4
Comments
Sergey Alexandrovich Kryukov 27-Mar-12 19:38pm    
You correctly explain how it works (I voted 4), but the answer is definitive "no"; please see my short answer. What is not clear is OP's thinking, but the answer is still the same, I think...
--SA
Philippe Mori 27-Mar-12 21:02pm    
I have added a third example in C++ that would update 2 variables using the ternary operator. I would not recommend that and C# does not allows it, but it might be what the OP was looking for. If it is the case, then he would have to use regular if/else.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900