← Back to C# Course | Chapter 3: Operators | Lesson 5 of 6

The Ternary Operator

In this page:

  1. The Ternary Operator

The Ternary Operator

The ternary operator condition ? valueIfTrue : valueIfFalse is a compact one-line alternative to a simple if/else. It always evaluates to exactly one of its two branches. Ternary expressions can be nested but doing so hurts readability quickly.

Note: Use ternary for short, simple value selection — fall back to if/else once logic gets complex.

Example: The Ternary Operator

markup
using System;

class Program
{
    static void Main(string[] args)
    {
        int age = 16;
        string status = age >= 18 ? "adult" : "minor";

        Console.WriteLine(status);
        Console.WriteLine(age % 2 == 0 ? "even" : "odd");
    }
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.