Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> C Language

C# Ternary Operator: A Concise Guide to Conditional Expressions

C# Ternary Operator

Master the C# ternary operator for compact, readable conditional logic.

The ternary operator is a succinct replacement for simple if…else statements. Before diving in, review C#’s if…else syntax if you’re new to it.

Syntax:

Condition ? Expression1 : Expression2;

How it works:

Example: Convert a multi‑line if…else into one line.

if (number % 2 == 0)
{
    isEven = true;
}
else
{
    isEven = false;
}

to:

isEven = (number % 2 == 0) ? true : false;

Why “ternary”?

It operates on three operands: the condition, the true branch, and the false branch.


Example 1: Basic Usage

using System;

namespace Conditional
{
    class Ternary
    {
        public static void Main(string[] args)
        {
            int number = 2;
            bool isEven;

            isEven = (number % 2 == 0) ? true : false;
            Console.WriteLine(isEven);
        }
    }
}

Output:

True

In this program, number is 2, so the condition evaluates to true, yielding isEven = true. The ternary can also return other types—strings, numbers, characters—making it versatile.

Directly printing the result is also possible:

Console.WriteLine((number % 2 == 0) ? true : false);

When to Use the Ternary Operator

The ternary operator is ideal for short, clear conditions. Overusing it can reduce readability, especially with nested expressions.

For example, a chain of if…else if can be condensed:

if (a > b)
{
    result = "a is greater than b";
}
else if (a < b)
{
    result = "b is greater than a";
}
else
{
    result = "a is equal to b";
}

to a single line:

result = a > b ? "a is greater than b" : a < b ? "b is greater than a" : "a is equal to b";

While this shortens the code, nested ternaries can become hard to follow. Use them sparingly for simple conditions; keep more complex logic in explicit if blocks.


C Language

  1. C# Operators – Comprehensive Guide to Operators in C#
  2. Mastering C# Operator Precedence & Associativity: A Practical Guide
  3. Master C++ Operator Overloading: Practical Examples & Best Practices
  4. Mastering Operator Overloading in Python: A Practical Guide
  5. Java instanceof Operator: A Comprehensive Guide
  6. C++ Operator Overloading – A Practical Guide with Code Examples
  7. Mastering C++ Overloading: Functions & Operators Explained
  8. Master MATLAB Basics: Essential Syntax & Commands
  9. Mastering Operator Overloading in C# for Custom Types
  10. Role of a 3D Printer Operator: Skills, Responsibilities, and Career Opportunities