Using Ternary Operators in C#
Last Update: Jun 7, 2024

AI changed software development. This is how the pros use it.
Written for working developers, Coding with AI goes beyond hype to show how AI fits into real production workflows. Learn how to integrate AI into Python projects, avoid hallucinations, refactor safely, generate tests and docs, and reclaim hours of development time—using techniques tested in real-world projects.
Most people don’t use ternary operators enough, or at all. I think it’s a better way of handling such expressions most of the time. For example:
We have a small console app:
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 10; i++)
{
Console.WriteLine(i);
}
}
}
This predictably outputs the numbers 1 through 10. But we’ll add some logic in here to identify even vs odd numbers:
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 10; i++)
{
string oddoreven;
if (i % 2 == 0) {
oddoreven = " even";
}else {
oddoreven = " odd";
}
Console.WriteLine(i + oddoreven);
}
}
Ok, not terribly complicated, but if we use a ternary operator, we can turn 6 lines into one:
Instead of this:
string oddoreven;
if (i % 2 == 0) {
oddoreven = " even";
}else {
oddoreven = " odd";
}
We now have this:
string oddoreven = (i % 2 == 0) ? " even " : " odd";
And the whole program looks like this:
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 10; i++)
{
string oddoreven = (i % 2 == 0) ? " even " : " odd";
Console.WriteLine(i + oddoreven);
}
}
}
See how much cleaner that is? If you have a file with tons of if-else statements you can save a ton of space by using ternary operators. Many folks say they’re harder to read but I just don’t see it. I think it’s much cleaner.
If you have more complicated conditional branching it doesn’t quite work as well but for many operations it does.
Note for Newbies
This is a simple code optimization, but it doesn’t make your program any faster. Many new programmers automatically assume less code is faster running code, but that’s not always the case.
In this case the compiler will build the exact same IL, however the optimization is for the programmers. This is how you should be optimizing your code anyway. Let the compiler figure out how to save cycles and you make the code more readable and easy to understand.
Questions, comments? Let me know!
Can you beat my SkillIQ Score in C#??

I think you can! Take the C# test here to see where you stand!

Skip the hype. The newsletter that keeps you in the know.
AI news curated for engineers. The AI New Hotness Newsletter is what you need.
Zero fluff. Just the research, tools, and infra updates that actually affect your production stack.
Stay up to date on AI for developers - Subscribe on LinkedIn





