How to use one-line if-else in C#?

By Josip Miskovic
A thumbnail showing one line if/else in C#.

How to use one-line if-else in C#?

To use a one-line if-else statement in C#, follow this syntax:

condition ? true_expression : false_expression;
C#
int result = isTrue ? 1 : 0;

This is equivalent to the following if-else statement:

C#
int result;
if (isTrue)
{
    result = 1;
}
else
{
    result = 0;
}

 

Ternary Operator

A one-line if-else statement is also called the ternary operator in C#.

It's called ternary because it has three operands:

  1. the condition,
  2. the expression that is evaluated if the condition is true, and
  3. the expression that is evaluated if the condition is false.

The ternary operator is a useful feature in C# that can help you write more concise and readable code in a variety of scenarios.

However, it's important to avoid too many condition chains to prevent your code from being overly complex or hard to read.

When to use the one-line if-else?

You can use one-line if-else statements in C# to write more concise code for simple conditional operations. For example, setting the value of a variable based on a single condition. However, for more complex scenarios, you should use a regular if-else statement or a switch statement to make your code more readable and maintainable.

Examples

Here are some examples of one-line if-else statements (ternary operators) in C#:

Null-Check

In this example we use IsNullOrEmpty to conditionally set the message variable:

C#
string message = !string.IsNullOrEmpty(name) ? "Hello, " + name : "Hello, stranger";

Method Invocation

C#
int value = 10;
bool isPositive = value > 0 ? IsPositive(value) : false;

Throwing Exceptions

You can also throw an exception in C# using a one-line if-else statement:

C#
int value = -1;
string message = value >= 0 ? "Value is positive" : throw new ArgumentException("Value must be non-negative");

Conditions chaining

You can also chain multiple conditions together using nested ternary operators:

C#
int value = 5;
string message = value < 0 ? "Value is negative" : value == 0 ? "Value is zero" : "Value is positive";
Josip Miskovic
About Josip

Josip Miskovic is a software developer at Americaneagle.com. Josip has 10+ years in experience in developing web applications, mobile apps, and games.

Read more posts →
Published on:
Download Free Software Developer Career Guide

I've used these principles to increase my earnings by 63% in two years. So can you.

Dive into my 7 actionable steps to elevate your career.