Conditional (?:) and Null-Coalescing (??) Operators in C# Programming
Introduction
The conditional operator (?:) and the null-coalescing operator (??) are used in C# to simplify decision-making and handle null values efficiently. This tutorial explains their usage with step-by-step examples.
Conditional Operator (?:)
The conditional operator evaluates a boolean expression and returns one of two values based on whether the condition is true or false. It is also known as the ternary operator.
Syntax:
condition ? value_if_true : value_if_false;
Example: Basic Conditional Operator
using System;
class Program
{
static void Main()
{
int number = 10;
string result = (number % 2 == 0) ? "Even" : "Odd";
Console.WriteLine("The number is: " + result);
}
}
Output:
The number is: Even
Example: Nested Conditional Operator
using System;
class Program
{
static void Main()
{
int score = 85;
string grade = (score >= 90) ? "A" :
(score >= 80) ? "B" :
(score >= 70) ? "C" : "F";
Console.WriteLine("The grade is: " + grade);
}
}
Output:
The grade is: B
Null-Coalescing Operator (??)
The null-coalescing operator is used to provide a default value when a nullable variable or reference type is null.
Syntax:
variable ?? default_value;
Example: Basic Null-Coalescing Operator
using System;
class Program
{
static void Main()
{
string? name = null;
string result = name ?? "Unknown";
Console.WriteLine("The name is: " + result);
}
}
Output:
The name is: Unknown
Example: Null-Coalescing with User Input
using System;
class Program
{
static void Main()
{
Console.WriteLine("Enter your name (or press Enter to skip):");
string? input = Console.ReadLine();
string name = string.IsNullOrWhiteSpace(input) ? "Guest" : input;
Console.WriteLine("Hello, " + name + "!");
}
}
Output (example):
Enter your name (or press Enter to skip):
John
Hello, John!
Combining Conditional and Null-Coalescing Operators
You can use both operators together to handle conditions and null values in a concise way.
Example: Combined Usage
using System;
class Program
{
static void Main()
{
int? number = null;
string result = (number ?? 0) > 50 ? "High" : "Low";
Console.WriteLine("The value is: " + result);
}
}
Output:
The value is: Low
Conclusion
The conditional operator (?:) and the null-coalescing operator (??) are essential tools for writing concise and readable C# code. Understanding their usage helps simplify complex decision-making logic and handle null values effectively.