8 minlesson

The Ternary Operator

The Ternary Operator

The ternary operator (? :) provides a concise way to write simple if-else statements as a single expression.

Syntax

csharp
1condition ? valueIfTrue : valueIfFalse

It's called "ternary" because it takes three operands:

  1. A condition
  2. A value if the condition is true
  3. A value if the condition is false

Basic Examples

csharp
1int age = 20;
2
3// Using if-else
4string status;
5if (age >= 18)
6{
7 status = "Adult";
8}
9else
10{
11 status = "Minor";
12}
13
14// Using ternary operator (same result)
15string status = age >= 18 ? "Adult" : "Minor";

More Examples

csharp
1int number = 7;
2
3// Check if even or odd
4string evenOdd = number % 2 == 0 ? "Even" : "Odd";
5Console.WriteLine($"{number} is {evenOdd}"); // 7 is Odd
6
7// Get absolute value (manual implementation)
8int value = -5;
9int absolute = value < 0 ? -value : value;
10Console.WriteLine(absolute); // 5
11
12// Choose between values
13int a = 10, b = 20;
14int max = a > b ? a : b;
15Console.WriteLine($"Max: {max}"); // Max: 20

Using with String Interpolation

csharp
1int itemCount = 3;
2
3// Pluralization
4Console.WriteLine($"You have {itemCount} item{(itemCount == 1 ? "" : "s")}");
5// Output: You have 3 items
6
7int cartCount = 1;
8Console.WriteLine($"You have {cartCount} item{(cartCount == 1 ? "" : "s")}");
9// Output: You have 1 item

Assigning to Variables

csharp
1bool isVIP = true;
2decimal discount = isVIP ? 0.20m : 0.10m;
3
4int score = 75;
5char grade = score >= 90 ? 'A' :
6 score >= 80 ? 'B' :
7 score >= 70 ? 'C' :
8 score >= 60 ? 'D' : 'F';
9
10Console.WriteLine($"Grade: {grade}"); // Grade: C

Nested Ternary (Use Sparingly)

You can nest ternary operators, but it can hurt readability:

csharp
1int age = 25;
2
3// Nested ternary - harder to read
4string category = age < 13 ? "Child" :
5 age < 20 ? "Teen" :
6 age < 65 ? "Adult" : "Senior";
7
8// Same logic with if-else - more readable
9string category;
10if (age < 13)
11 category = "Child";
12else if (age < 20)
13 category = "Teen";
14else if (age < 65)
15 category = "Adult";
16else
17 category = "Senior";

Recommendation: Use nested ternary sparingly. If it's complex, use if-else instead.

Ternary with Method Calls

csharp
1bool isUrgent = true;
2
3// Choose which method to call
4SendNotification(isUrgent ? "URGENT: Check now!" : "Regular update");
5
6// Choose message based on condition
7void SendNotification(string message)
8{
9 Console.WriteLine($"Notification: {message}");
10}

Ternary in Return Statements

csharp
1bool IsEven(int number)
2{
3 return number % 2 == 0;
4}
5
6// Or more concisely
7bool IsPositive(int number) => number > 0;
8
9string GetGreeting(bool isMorning) => isMorning ? "Good morning!" : "Hello!";

Null-Coalescing Operator (??)

Related to ternary, ?? provides a default for null values:

csharp
1string? name = null;
2
3// Using ternary
4string displayName1 = name != null ? name : "Guest";
5
6// Using null-coalescing (cleaner)
7string displayName2 = name ?? "Guest";

Null-Coalescing Assignment (??=)

csharp
1string? userName = null;
2
3// Assign only if null
4userName ??= "Guest";
5
6Console.WriteLine(userName); // Guest

When to Use Ternary

Good Use Cases

csharp
1// Simple value selection
2string status = isActive ? "Active" : "Inactive";
3
4// Inline in string interpolation
5Console.WriteLine($"Status: {(count > 0 ? "Has items" : "Empty")}");
6
7// Default values
8int timeout = customTimeout > 0 ? customTimeout : 30;
9
10// Simple conditional return
11public string GetLabel(bool isNew) => isNew ? "NEW" : "";

Avoid Ternary When

csharp
1// Don't use for side effects
2// Bad:
3bool success = condition
4 ? (DoSomething(), true).Item2
5 : (DoSomethingElse(), false).Item2;
6
7// Use if-else instead:
8bool success;
9if (condition)
10{
11 DoSomething();
12 success = true;
13}
14else
15{
16 DoSomethingElse();
17 success = false;
18}
19
20// Don't over-nest
21// Bad:
22var x = a ? (b ? 1 : 2) : (c ? 3 : (d ? 4 : 5));
23
24// Use if-else for complex logic

Practical Examples

csharp
1// Displaying user status
2bool isOnline = true;
3Console.WriteLine($"User is {(isOnline ? "online" : "offline")}");
4
5// Fee calculation
6bool isMember = true;
7decimal fee = isMember ? 0.00m : 5.00m;
8
9// Formatting numbers
10int value = -42;
11string formatted = $"{(value >= 0 ? "+" : "")}{value}";
12Console.WriteLine(formatted); // -42
13
14// Choosing colors
15int level = 3;
16string color = level == 1 ? "Green" :
17 level == 2 ? "Yellow" :
18 level == 3 ? "Red" : "Unknown";

Summary

In this lesson, you learned:

  • Ternary operator syntax: condition ? trueValue : falseValue
  • Use it for simple, inline conditional expressions
  • Works well with string interpolation
  • Related: ?? for null defaults, ??= for null assignment
  • Avoid complex nested ternary for readability

Next, we'll explore switch statements for handling multiple conditions.