C# If...Else (Ternary Operator)

In C#, the ternary operator is a shorthand way of writing an if...else statement. It is a compact way to write simple if...else statements that assign a value to a variable depending on a condition.

The syntax of the ternary operator is as follows:

1variable = (condition) ? expressionTrue : expressionFalse;
  • condition is the expression to be evaluated.
  • expressionTrue is the value assigned to the variable if the condition is true.
  • expressionFalse is the value assigned to the variable if the condition is false.

Here's an example:

1int x = 10; 2string result = (x > 5) ? "x is greater than 5" : "x is less than or equal to 5"; 3Console.WriteLine(result);

In the above example, the condition x > 5 is evaluated. If it is true, the value "x is greater than 5" is assigned to the result variable. If it is false, the value "x is less than or equal to 5" is assigned to the result variable.

The ternary operator can be used in place of simple if...else statements to make your code more concise and easier to read. However, it is not recommended to use the ternary operator for complex if...else statements, as it can make your code less readable.

Here's another example that shows how the ternary operator can be used to assign a value to a variable:

1int a = 5; 2int b = 10; 3int max = (a > b) ? a : b; 4Console.WriteLine(max);

In the above example, the variable max is assigned the value of a if a > b is true, and the value of b if it is false.

The ternary operator can also be used in place of a simple if statement, like this:

1int x = 5; 2string message = (x == 5) ? "x is 5" : null; 3Console.WriteLine(message);

In the above example, the value of the message variable is assigned "x is 5" if x == 5 is true, and null if it is false.