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
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With