In C#, you can write a shorthand version of an if statement using the ternary operator (? :
). The syntax for a shorthand if statement is:
condition ? expressionIfTrue : expressionIfFalse;
Here's an example:
int number = 10;
string message = (number > 5) ? "Number is greater than 5" : "Number is less than or equal to 5";
In this example, the condition is (number > 5)
. If the condition is true, the expression expressionIfTrue
is executed, which in this case is the string "Number is greater than 5". If the condition is false, the expression expressionIfFalse
is executed, which in this case is the string "Number is less than or equal to 5".
The resulting string variable message
will contain the value "Number is greater than 5", because the condition number > 5
is true.
Comments
Post a Comment