C# Basics: The Conditional or Ternary Operator

by Tyler Jensen 15. September 2011 02:20

For the second installment of C# Basics, let’s take a look at the conditional operator, sometimes known as the ternary operator. How many times have you written code like this:

if (a == b)
{
  x = y;
}
else
{
  x = z;
}

Probably never, at least not quite this simplistic or with such ancient style variable names, or one would hope anyway. But the example serves its purpose. Now use the conditional operator and convert that code to this:

x = (a == b) ? y : z;

You can read more about the conditional operator on MSDN here.

Tags:

C# Basics | Code | Software Development

blog comments powered by Disqus

Me...

Tyler Jensen

Tyler Jensen
.NET Developer and Architect

Month List

Other Stuff