c# ternary operator

[print-me]

The c# ternary operator (?:) in C# does the same thing as the if else statement though it is more suited on simple statements such as assigning two different values depending on a specified condition. Below shows the syntax of using this operator.

<condition> ? <result if true> : <result if false>

The conditional operator is C#’s only ternary operator as it requires three operands, the condition, the value when the condition is true, and the value when the condition is false. Let’s take a look at how to use this operator inside a program.

namespace ConditionalOperatorDemo
{
    public class Program
    {
        public static void Main()
        {
            string pet1 = "puppy";
            string pet2 = "kitten";
            string type1;
            string type2;

            type1 = (pet1 == "puppy") ? "dog" : "cat";
            type2 = (pet2 == "kitten") ? "cat" : "dog";
        }
    }
}

Example 1 – Using the Conditional Operator

The above program demonstrates the use of the conditional operator. The first line translates like this; if the value of pet1 is “puppy” then assign “dog” to type1, otherwise, assign “cat” to type1. Same goes with the second line; if the value of pet2 is “kitten” then assign “cat” to type2, “dog” otherwise. Let’s transform the following line of code to its equivalent if else statement to make it even clearer.

If we rewrite this using if else statement, it will look like this.

if (pet1 == "puppy")
   type1 = "dog";
else
   type1 = "cat";

Avoid using the conditional operator when you have multiple statements inside an if  or else block. Sometimes, the conditional operator can make code less readable.