Skip to main content

How to Use the Conditional Operator ?: in C#

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

When a value depends on a condition, such as "Good morning" before noon and "Good afternoon" after, an if and else that each assign a variable takes six lines. The conditional operator, condition ? a : b, picks the value in one expression.

Syntax​

Syntax
<Type> <result> = <condition> ? <valueIfTrue> : <valueIfFalse>;
PartWhat it does
<condition>A bool expression, such as hour < 12.
? <valueIfTrue>The result when the condition is true.
: <valueIfFalse>The result when the condition is false.

Microsoft's conditional operator reference: "The conditional operator ?:, also known as the ternary conditional operator, evaluates a Boolean expression and returns the result of one of the two expressions, depending on whether the Boolean expression evaluates to true or false". Only the chosen value is worked out at all; the reference: "Only consequent or alternative is evaluated."

The Example​

The example greets someone depending on the hour, which is 14, and then greets a person whose name may be missing, inside an interpolated string.

Prerequisites​

  • The .NET 10 SDK or newer, which runs a single .cs file with dotnet run. This guide uses .NET SDK 10.0.404.

Step 1: Write the Code​

Create a file named main.cs in an empty folder:

main.cs, which sets hour to 14 and picks Good morning or Good afternoon with hour less than 12 as the condition, then prints Hi with there when name is null, using the conditional operator in parentheses inside an interpolated string.

main.cs
var hour = 14;
string greeting = hour < 12 ? "Good morning" : "Good afternoon";
Console.WriteLine(greeting);

string? name = null;
Console.WriteLine($"Hi {(name is null ? "there" : name)}!");

Inside an interpolated string, the conditional operator goes in parentheses, because a colon there would otherwise start a format string.

Step 2: Run It​

Terminal
dotnet run main.cs
Output
Good afternoon
Hi there!

A zsh terminal where dotnet run main.cs prints Good afternoon and Hi there!

14 < 12 is false, so the operator returned the value after the colon, Good afternoon. name is null was true, so the second line used there. The command is the same in zsh, bash and PowerShell.

What Happens When the Types Don't Match​

Both values must be able to become one type. A number and a string can't:

main.cs
bool useNumber = true;
var label = useNumber ? 1 : "one";
Console.WriteLine(label);
Output
/Users/you/demo/main.cs(2,13): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and 'string'

The build failed. Fix the build errors and run again.

var gives the result no type to aim for, so C# needs the two values to share one. Make both values the same type, such as "1" and "one". Or declare the type both values convert to: object label = useNumber ? 1 : "one"; compiles and prints 1, because, as the reference puts it, "Conditional expressions are target-typed."

Common Mistakes​

MistakeWhat happensDo this instead
Returning values of unrelated typeserror CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and 'string'Give both values the same type
Writing the operator inside {...} of an interpolated string without parenthesesThe colon is read as the start of a format stringWrap it: {(name is null ? "there" : name)}
Nesting several conditional operators on one lineThe line is hard to read and easy to get wrongUse if and else, or a switch expression

Troubleshooting​

SymptomLikely causeFix
CS0173The two values have different typesConvert one so both match
The wrong value comes backThe condition is reversedRead it as "if condition, then the first value, else the second"

FAQ​

Can I nest conditional operators?​

Yes. The reference: "The conditional operator is right-associative", so a ? b : c ? d : e is evaluated as a ? b : (c ? d : e). Two or three levels quickly get hard to read, though.

When should I use if instead?​

When each branch does something, such as calling methods or printing, rather than producing a value. The conditional operator is for choosing a value.

Conclusion​

condition ? valueIfTrue : valueIfFalse chooses between two values in one expression. Keep the two values the same type, put the operator in parentheses inside interpolated strings, and switch to if when the branches do more than pick a value.

Additional Resources​