2.6: Ternary Operators

In this module we'll take a look at ternary operators.

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 0.02_Ternary_Operators

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

About

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.

    class Program
    {
        static void Main(string[] args)
        {
            int number = 10;
                                    //1     //2       //3               //4
            string response = ((number == 7) ? "The number is 7." : "The number is not 7.");
            Console.WriteLine(response);
        }
    }

Discussion

  1. We have an expression asking if the number is 7.

  2. Then, we use the ternary operator ? to allow us to set up a comparison.

  3. Before the colon, we show this if it is true.

  4. If false, the value is what we have after the colon.

Here is the basic format of a ternary expression:

  • ((value that we're checking for true or false) ? do this if true : do this if false);

Next: Ternary Expressions

Last updated