The Ternary Operator
The ternary operator (? :) provides a concise way to write simple if-else statements as a single expression.
Syntax
csharp1condition ? valueIfTrue : valueIfFalse
It's called "ternary" because it takes three operands:
- A condition
- A value if the condition is true
- A value if the condition is false
Basic Examples
csharp1int age = 20;23// Using if-else4string status;5if (age >= 18)6{7 status = "Adult";8}9else10{11 status = "Minor";12}1314// Using ternary operator (same result)15string status = age >= 18 ? "Adult" : "Minor";
More Examples
csharp1int number = 7;23// Check if even or odd4string evenOdd = number % 2 == 0 ? "Even" : "Odd";5Console.WriteLine($"{number} is {evenOdd}"); // 7 is Odd67// Get absolute value (manual implementation)8int value = -5;9int absolute = value < 0 ? -value : value;10Console.WriteLine(absolute); // 51112// Choose between values13int a = 10, b = 20;14int max = a > b ? a : b;15Console.WriteLine($"Max: {max}"); // Max: 20
Using with String Interpolation
csharp1int itemCount = 3;23// Pluralization4Console.WriteLine($"You have {itemCount} item{(itemCount == 1 ? "" : "s")}");5// Output: You have 3 items67int cartCount = 1;8Console.WriteLine($"You have {cartCount} item{(cartCount == 1 ? "" : "s")}");9// Output: You have 1 item
Assigning to Variables
csharp1bool isVIP = true;2decimal discount = isVIP ? 0.20m : 0.10m;34int score = 75;5char grade = score >= 90 ? 'A' :6 score >= 80 ? 'B' :7 score >= 70 ? 'C' :8 score >= 60 ? 'D' : 'F';910Console.WriteLine($"Grade: {grade}"); // Grade: C
Nested Ternary (Use Sparingly)
You can nest ternary operators, but it can hurt readability:
csharp1int age = 25;23// Nested ternary - harder to read4string category = age < 13 ? "Child" :5 age < 20 ? "Teen" :6 age < 65 ? "Adult" : "Senior";78// Same logic with if-else - more readable9string category;10if (age < 13)11 category = "Child";12else if (age < 20)13 category = "Teen";14else if (age < 65)15 category = "Adult";16else17 category = "Senior";
Recommendation: Use nested ternary sparingly. If it's complex, use if-else instead.
Ternary with Method Calls
csharp1bool isUrgent = true;23// Choose which method to call4SendNotification(isUrgent ? "URGENT: Check now!" : "Regular update");56// Choose message based on condition7void SendNotification(string message)8{9 Console.WriteLine($"Notification: {message}");10}
Ternary in Return Statements
csharp1bool IsEven(int number)2{3 return number % 2 == 0;4}56// Or more concisely7bool IsPositive(int number) => number > 0;89string GetGreeting(bool isMorning) => isMorning ? "Good morning!" : "Hello!";
Null-Coalescing Operator (??)
Related to ternary, ?? provides a default for null values:
csharp1string? name = null;23// Using ternary4string displayName1 = name != null ? name : "Guest";56// Using null-coalescing (cleaner)7string displayName2 = name ?? "Guest";
Null-Coalescing Assignment (??=)
csharp1string? userName = null;23// Assign only if null4userName ??= "Guest";56Console.WriteLine(userName); // Guest
When to Use Ternary
Good Use Cases
csharp1// Simple value selection2string status = isActive ? "Active" : "Inactive";34// Inline in string interpolation5Console.WriteLine($"Status: {(count > 0 ? "Has items" : "Empty")}");67// Default values8int timeout = customTimeout > 0 ? customTimeout : 30;910// Simple conditional return11public string GetLabel(bool isNew) => isNew ? "NEW" : "";
Avoid Ternary When
csharp1// Don't use for side effects2// Bad:3bool success = condition4 ? (DoSomething(), true).Item25 : (DoSomethingElse(), false).Item2;67// Use if-else instead:8bool success;9if (condition)10{11 DoSomething();12 success = true;13}14else15{16 DoSomethingElse();17 success = false;18}1920// Don't over-nest21// Bad:22var x = a ? (b ? 1 : 2) : (c ? 3 : (d ? 4 : 5));2324// Use if-else for complex logic
Practical Examples
csharp1// Displaying user status2bool isOnline = true;3Console.WriteLine($"User is {(isOnline ? "online" : "offline")}");45// Fee calculation6bool isMember = true;7decimal fee = isMember ? 0.00m : 5.00m;89// Formatting numbers10int value = -42;11string formatted = $"{(value >= 0 ? "+" : "")}{value}";12Console.WriteLine(formatted); // -421314// Choosing colors15int 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.