Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add an if statement to a parameter?

Tags:

c#

Is there any way to add an if statement into a function parameter? For example:

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
like image 421
C0d1ng Avatar asked May 23 '16 22:05

C0d1ng


Video Answer


2 Answers

You are looking for the conditional operator or ternary operator ?::

Its form is

condition ? value_if_true : value_if_false

For example:

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

Or my personal preference,

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

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

Note that you cannot put arbitrary code for value_if_true and value_if_false -- it has to be an expression, not a statement. So the above is valid because

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

is a 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, because Console.Write(..) does not return a value, or

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

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

like image 194
CompuChip Avatar answered Sep 28 '22 03:09

CompuChip


You might be looking for the ternary expression.

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

Is equivalent to:

Console.WriteLine(thisIsTrue ? "this" : "that") 
like image 36
Nathan Taylor Avatar answered Sep 28 '22 03:09

Nathan Taylor