Skip to main content

How to Nest the Conditional Operator ?: in C#

· 9 min read
Jagdish Kumawat
Founder @ Dewiride

One ?: picks one of two results. To pick from three or more, put another ?: after each :, one condition per line, and finish the chain with the result for everything else, or with a throw for a value that should never happen.

The conditional operator picks a result by testing a condition. The C# specification: The ?: operator is called the conditional operator. It is at times also called the ternary operator. It describes how one works: A conditional expression of the form b ? x : y first evaluates the condition b. Then, if b is true, x is evaluated and becomes the result of the operation. Otherwise, y is evaluated and becomes the result of the operation.

To choose from more than two results, make y another conditional expression, and repeat. Each new ? adds one more condition, and the chain ends with a last result for when no condition is true.

Syntax​

Syntax
<condition1> ? <result1>
: <condition2> ? <result2>
: <condition3> ? <result3>
: <lastResult>
PartWhat it is
<condition1>A bool expression. C# checks it first
? <result1>The result when <condition1> is true
: <condition2> ? <result2>Another conditional expression. C# reaches it only when <condition1> is false
: <condition3> ? <result3>One more condition and its result. Add as many lines like this as you need
: <lastResult>The result when no condition is true: a value, or a throw expression

The Example​

A console app called NestedConditional has a Describe function that turns the number of items in a shopping cart into a sentence: one for an empty cart, one for a single item, and one for more than one item. A cart can't hold fewer than 0 items, so the chain ends by throwing an exception for a negative count. The app describes carts with 0, 1 and 5 items, then tries -2.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n NestedConditional
cd NestedConditional
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/NestedConditional/NestedConditional.csproj:
Determining projects to restore...
Restored /Users/you/source/NestedConditional/NestedConditional.csproj (in 45 ms).
Restore succeeded.

dotnet new console -n NestedConditional creates a folder named NestedConditional with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or NestedConditional.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the three carts:

Program.cs (three carts)
// Describe a cart with 0, 1 and 5 items.
int[] counts = [0, 1, 5];
foreach (int count in counts)
Console.WriteLine($"{count}: {Describe(count)}");

counts holds 0, 1 and 5, and the loop prints each count with the sentence that Describe returns for it. Describe is at the end of the file.

Then a count that isn't allowed:

Program.cs (a negative count)
// A negative count reaches the throw at the end.
try
{
Console.WriteLine(Describe(-2));
}
catch (ArgumentOutOfRangeException error)
{
Console.WriteLine($"-2: {error.Message}");
}

Describe(-2) throws an ArgumentOutOfRangeException, as the end of the chain shows below. The catch block catches it and prints its Message.

Then the chain:

Program.cs (the chain)
// The conditions are checked from the top, and the first true one picks the result.
static string Describe(int items) =>
items == 0 ? "The cart is empty"
: items == 1 ? "1 item in the cart"
: items > 1 ? $"{items} items in the cart"

static string Describe(int items) => declares a function that takes a number of items and returns a string. Its whole body is one expression after =>: the chain, written with one condition per line.

C# checks items == 0 first. When it's true, the result is The cart is empty, and the rest of the chain doesn't run. The C# specification: A conditional expression never evaluates both x and y. When it's false, the result is everything after the next :, which is another conditional expression that checks items == 1, and then items > 1 the same way. So the conditions are checked from the top, and the first one that's true picks the result.

Last, what's left:

Program.cs (the throw at the end)
: throw new ArgumentOutOfRangeException(nameof(items), "A cart can't hold fewer than 0 items.");

A count that fails all three conditions is below 0, so the last part throws an exception instead of returning a sentence. The C# specification lists the places where a throw expression can go, and this is one of them: As the second or third operand of a ternary conditional operator (?:). new ArgumentOutOfRangeException(nameof(items), "...") uses the constructor that the API reference describes as: Initializes a new instance of the ArgumentOutOfRangeException class with the name of the parameter that causes this exception and a specified error message. nameof(items) gives the parameter's name, items.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
0: The cart is empty
1: 1 item in the cart
5: 5 items in the cart
-2: A cart can't hold fewer than 0 items. (Parameter 'items')

macOS-style terminal window titled Terminal — NestedConditional showing dotnet run printing 0: The cart is empty, 1: 1 item in the cart, 5: 5 items in the cart, and -2: A cart can't hold fewer than 0 items. (Parameter 'items')

Each count got the result of the first condition that was true for it: 0 gave The cart is empty, 1 gave 1 item in the cart, and 5 gave 5 items in the cart. -2 failed all three conditions and reached the throw, so the catch printed the exception's message, A cart can't hold fewer than 0 items., with (Parameter 'items') added from the parameter name.

The Complete File​

macOS-style code window titled Program.cs — NestedConditional showing a loop that describes carts with 0, 1 and 5 items, a try and catch block that calls Describe with -2, and a Describe function whose body chains three conditional operators, one per line, ending in throw new ArgumentOutOfRangeException

Program.cs
// Describe a cart with 0, 1 and 5 items.
int[] counts = [0, 1, 5];
foreach (int count in counts)
Console.WriteLine($"{count}: {Describe(count)}");

// A negative count reaches the throw at the end.
try
{
Console.WriteLine(Describe(-2));
}
catch (ArgumentOutOfRangeException error)
{
Console.WriteLine($"-2: {error.Message}");
}

// The conditions are checked from the top, and the first true one picks the result.
static string Describe(int items) =>
items == 0 ? "The cart is empty"
: items == 1 ? "1 item in the cart"
: items > 1 ? $"{items} items in the cart"
: throw new ArgumentOutOfRangeException(nameof(items), "A cart can't hold fewer than 0 items.");

Common Mistakes​

MistakeWhat happensDo this instead
Putting a general condition before a special oneWith items > 0 ? above items == 1 ?, a cart with 1 item printed 1: 1 items in the cart. items > 0 was already true, so the chain never reached items == 1Put the special case first. In the example's order, 1 printed 1: 1 item in the cart
Leaving out the last partA chain that ended with : items == 1 ? "1 item in the cart"; stopped the build with error CS1003: Syntax error, ':' expected and error CS1525: Invalid expression term ';'Every ? needs its :. End the chain with : <lastResult>, a value or a throw expression

FAQ​

Where does C# put the parentheses in a chain?​

On the right. The C# specification: The conditional operator is right-associative, meaning that operations are grouped from right to left. Its example: An expression of the form a ? b : c ? d : e is evaluated as a ? b : (c ? d : e). So each : takes the whole rest of the chain as its result. Here's Describe with those parentheses written out:

Program.cs
static string Describe(int items) =>
items == 0 ? "The cart is empty"
: (items == 1 ? "1 item in the cart"
: (items > 1 ? $"{items} items in the cart"
: throw new ArgumentOutOfRangeException(nameof(items), "A cart can't hold fewer than 0 items.")));
Output
0: The cart is empty
1: 1 item in the cart
5: 5 items in the cart

It printed the same three lines as the example, so you don't need to type the parentheses.

Can the throw come first?​

Yes. A throw expression can also be the second operand, the result after ?. This version checks for a negative count first and ends with the sentence for more than one item:

Program.cs
static string Describe(int items) =>
items < 0 ? throw new ArgumentOutOfRangeException(nameof(items), "A cart can't hold fewer than 0 items.")
: items == 0 ? "The cart is empty"
: items == 1 ? "1 item in the cart"
: $"{items} items in the cart";
Output
0: The cart is empty
1: 1 item in the cart
5: 5 items in the cart

The three carts printed the same sentences as before.

Conclusion​

To choose from more than two results with ?:, put another conditional expression after each :, one condition per line, with the special cases first, because the first condition that's true wins. End the chain with a last result, or with a throw for a value that should never happen. Keep each part short. Microsoft's guide to operators: Use ?: for simple, inline choices. For multi-way conditions or blocks of code, an if/else statement is usually clearer.

Additional Resources​