DevAcademia
C++C#CPythonJava
  • C# Basics

  • C# Introduction
  • C# Get Started
  • C# Syntax
  • C# Output
  • C# Comments
  • C# Variables
  • C# Data Types
  • C# Type Casting
  • C# User Input
  • C# Operators
  • C# Math
  • C# Strings
  • C# Booleans
  • C# If...Else
  • C# Switch Statement
  • C# While Loop
  • C# For Loop
  • C# Break and Continue
  • C# Arrays
  • C# Files
  • C# OOP

  • C# OOP Introduction
  • C# Classes and Objects
  • C# Class Members
  • C# Constructors
  • C# Destructors
  • C# Access Modifiers
  • C# Properties
  • C# Inheritance
  • C# Polymorphism
  • C# Abstraction
  • C# Interfaces
  • C# Enums
  • C# Exceptions
  • C# Quizzes

  • C# Quiz Introduction
  • C# Basics

  • C# Introduction
  • C# Get Started
  • C# Syntax
  • C# Output
  • C# Comments
  • C# Variables
  • C# Data Types
  • C# Type Casting
  • C# User Input
  • C# Operators
  • C# Math
  • C# Strings
  • C# Booleans
  • C# If...Else
  • C# Switch Statement
  • C# While Loop
  • C# For Loop
  • C# Break and Continue
  • C# Arrays
  • C# Files
  • C# OOP

  • C# OOP Introduction
  • C# Classes and Objects
  • C# Class Members
  • C# Constructors
  • C# Destructors
  • C# Access Modifiers
  • C# Properties
  • C# Inheritance
  • C# Polymorphism
  • C# Abstraction
  • C# Interfaces
  • C# Enums
  • C# Exceptions
  • C# Quizzes

  • C# Quiz Introduction

Loading Cs tutorial…

Loading content
C# BasicsTopic 28 of 55
←PreviousPrevNextNext→

C# Ternary Operator (Shorthand if-else) - Complete Guide

Introduction to Ternary Operator

The ternary operator (?:) in C# provides a concise way to write simple conditional statements. It is often called the conditional operator and allows you to choose between two values based on a condition, all in a single line.

It improves code compactness and readability for straightforward cases, but nested or complex ternary expressions should be avoided for clarity.

Basic Ternary Operator Syntax

The ternary operator syntax is: condition ? value_if_true : value_if_false

Example
using System;

namespace TernaryOperatorExample
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 10;
            string result = (number > 5) ? "Greater than 5" : "5 or less";
            Console.WriteLine(result);

            int age = 20;
            string status;

            if (age >= 18)
                status = "Adult";
            else
                status = "Minor";
            Console.WriteLine($"Using if-else: {status}");

            status = (age >= 18) ? "Adult" : "Minor";
            Console.WriteLine($"Using ternary: {status}");

            Console.WriteLine($"The number is {(number % 2 == 0 ? "even" : "odd")}");

            double price = 99.99;
            string message = (price > 100) ? "Expensive" : "Affordable";
            Console.WriteLine(message);

            bool isEven = (number % 2 == 0) ? true : false;
            Console.WriteLine($"Is number even? {isEven}");

            int discount = (price > 50) ? 10 : 5;
            Console.WriteLine($"Discount: {discount}%");
        }
    }
}
Output
Greater than 5
Using if-else: Adult
Using ternary: Adult
The number is even
Affordable
Is number even? True
Discount: 10%

Advanced Ternary Operator Usage

The ternary operator can also be used for grading, selecting maximum values, handling null values, and inline expressions. However, readability should always be considered.

Example
using System;

namespace AdvancedTernaryExample
{
    class Program
    {
        static void Main(string[] args)
        {
            int score = 85;
            string grade = (score >= 90) ? "A" :
                          (score >= 80) ? "B" :
                          (score >= 70) ? "C" :
                          (score >= 60) ? "D" : "F";
            Console.WriteLine($"Score: {score}, Grade: {grade}");

            int x = 10, y = 20;
            int max = (x > y) ? x : y;
            Console.WriteLine($"Maximum: {max}");

            string name = null;
            string displayName = (name != null) ? name : "Guest";
            Console.WriteLine($"Welcome, {displayName}!");

            displayName = name ?? "Guest";
            Console.WriteLine($"Welcome, {displayName}!");

            int a = 5, b = 10, c = 15;
            string comparison = (a < b && b < c) ? "Numbers are in order" : "Numbers are not in order";
            Console.WriteLine(comparison);

            Console.WriteLine($"Is positive: {IsPositive(-5)}");
            Console.WriteLine($"Is positive: {IsPositive(5)}");

            string input = "hello";
            string processed = (input.Length > 3) ? input.ToUpper() : input.ToLower();
            Console.WriteLine(processed);

            int value = 7;
            var (description, color) = (value % 2 == 0) ? ("even", "blue") : ("odd", "red");
            Console.WriteLine($"{value} is {description} and represented by {color}");
        }

        static string IsPositive(int number) => (number > 0) ? "Yes" : "No";
    }
}
Output
Score: 85, Grade: B
Maximum: 20
Welcome, Guest!
Welcome, Guest!
Numbers are in order
Is positive: No
Is positive: Yes
HELLO
7 is odd and represented by red

When to Use and Avoid Ternary Operator

The ternary operator is best for simple conditions. Avoid it when logic is complex, involves multiple statements, or side effects, as it can harm readability.

Example
using System;

namespace TernaryBestPractices
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 10;
            string parity = (number % 2 == 0) ? "even" : "odd";
            Console.WriteLine(parity);

            int absoluteValue = (number >= 0) ? number : -number;
            Console.WriteLine(absoluteValue);

            int x = 5, y = 10, z = 15;
            string complexResult = (x > y && y < z) ? "Condition 1" : 
                                  (x == y || y > z) ? "Condition 2" : "Default";
            Console.WriteLine(complexResult);

            string betterResult;
            if (x > y && y < z)
                betterResult = "Condition 1";
            else if (x == y || y > z)
                betterResult = "Condition 2";
            else
                betterResult = "Default";
            Console.WriteLine(betterResult);

            int value = -5;
            if (value < 0)
            {
                Console.WriteLine("Value is negative");
                value = Math.Abs(value);
                Console.WriteLine("Converted to positive");
            }

            int counter = 0;
            if (counter > 0)
            {
                Console.WriteLine("Counter is positive");
                counter++;
            }
            else
            {
                Console.WriteLine("Counter is zero or negative");
                counter--;
            }

            int age = 20;
            string canVote = (age >= 18) ? "Yes" : "No";
            Console.WriteLine($"Can vote: {canVote}");
        }
    }
}
Output
even
10
Default
Default
Value is negative
Converted to positive
Counter is zero or negative
Can vote: Yes
Test your knowledge: C# Ternary Operator (Shorthand if-else) - Complete Guide
Quiz Configuration
4 of 8 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 5 min
C# BasicsTopic 28 of 55
←PreviousPrevNextNext→