Is it possible to add an if parameter to a parameter?

Is there a way to add an if statement to a function parameter? For instance:

static void Main() { bool Example = false; Console.Write((if(!Example){"Example is false"}else{"Example is true"})); } //Desired outcome of when the code shown above is //executed would be for the console to output: //Example is false 
+5
source share
4 answers

Are you looking for a conditional operator or a three-dimensional operator ?: ::

His form

 condition ? value_if_true : value_if_false 

For instance:

 Console.Write((!Example) ? "Example is false" : "Example is true"); 

Or my personal preferences,

 Console.Write(Example ? "Example is true" : "Example is false"); 

so that I never think what happens when "not Example is false".

Note that you cannot put arbitrary code for value_if_true and value_if_false - it must be an expression, not an expression. So the above is true because

 (!Example) ? "Example is false" : "Example is true" 

is string , you can write:

 string message = (!Example) ? "Example is false" : "Example is true"; Console.Write(message); 

However you cannot do

 (!Example) ? Console.Write("Example is false") : Console.Write("Example is true") 

for example, since Console.Write(..) does not return a value, or

 (!Example) ? { a = 1; "Example is false" } : "Example is true" 

because { a = 1; "Example is false" } { a = 1; "Example is false" } not an expression.

+6
source

You may be looking for a thermal expression.

 if (thisIsTrue) Console.WriteLine("this") else Console.WriteLine("that") 

It is equivalent to:

 Console.WriteLine(thisIsTrue ? "this" : "that") 
+5
source
 Console.Write(Example?"Example is true":"Example is false"); 

or even

 Console.Write("Example is " + (Example?"True":"False")); 
+1
source

Sorry air code, I'm using a tablet.

You can do what you want with the ternary operator ( https://msdn.microsoft.com/en-us/library/ty67wk28.aspx ) as follows:

 Console.Write(!Example?"Example is false":"Example is true"); 

Basically, it acts like a built-in if statement. If the part before the question mark is true, you get a bit between the question mark and the colon. If false, you get the bit after the colon.

If this does not make sense, send the message back, and I will try to provide a clearer example when I am on a real computer.

+1
source

All Articles