7.3: Ternary Expressions

In this module we'll study ternary expressions.

File Location

  1. Right click on the solution you made in the first module.

  2. Go to Add > New Project and select Console App (.NET Framework).

  3. Name it 07_conditionals_ternary_expressions.

  4. Write your code for this module within Program.cs of that project.

Ternary Expressions

Ternary Expressions are simply a different way to write if statements. They provide less lines of code, reduce nesting, and therefore help your program run faster and more efficiently.

Example:

class Program
{
    static void Main(string[] args)
    {
        int number = 10;

        //If Else Statement
        if (number == 7)
            Console.WriteLine("The number is 7.");
        else
            Console.WriteLine("The number is not 7.");

        //Ternary Expression:
                            //1        //2    //3           //4    //5
        string response = ((number == 7) ? "The number is 7." : "The number is not 7.");
        Console.WriteLine(response);
    }
}

Discussion

  1. In the above lines of code, we have an expression asking if the number is 7.

  2. We then use the ternary operator ? to identify that a ternary expression is coming.

  3. If the expression is true, we return The number is 7.

  4. We use a colon to separate options. Think of the left side as the if and the right side as the else.

  5. If the expression is false, we return The number is not 7.

  6. Here is the basic format of a ternary expression:

    • ((question) ? do if true : do if false);

Further Practice

Try to make some conditional statements of your own. Don't worry about making them too complicated. Try any or all of the following, and when you feel like you're ready, move on to the next module:

  • Switch Cases

  • If and else if statements

  • Ternary Expressions

Last updated