Last Update: Dec 31, 2022

Check out my YouTube Channel!

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#??

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





Published: Oct 30, 2012 by Jeremy Morgan. Contact me before republishing this content.