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

The Ternary Operator

The ternary operator is a short one-line choice: 'is it raining? take an umbrella, otherwise take sunglasses'. It picks between two values without a full if-else.

In this page:

  1. The Ternary Operator
Syntax
csharp
type result = condition ? valueIfTrue : valueIfFalse;

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");
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Nesting several ?: operators so the code becomes hard to read.
  2. Using branches of different types that have no common type, which is a compile error.
  3. Using the ternary operator as a statement instead of an expression, such as x > 0 ? Print() : Skip();.
🔒

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.