0
0
C Sharp (C#)programming~5 mins

Null-coalescing operator in C Sharp (C#)

Choose your learning style9 modes available
Introduction

The null-coalescing operator helps you pick a value that is not null easily. It gives a simple way to choose a default value when something might be missing.

When you want to use a default value if a variable is null.
When reading user input that might be empty or missing.
When working with data that can be optional or not set.
When you want to avoid writing long if-else checks for null.
When you want cleaner and shorter code for fallback values.
Syntax
C Sharp (C#)
var result = value ?? defaultValue;

The operator is written as two question marks: ??.

If value is not null, it is used; otherwise, defaultValue is used.

Examples
If name is null, displayName becomes "Guest".
C Sharp (C#)
string name = null;
string displayName = name ?? "Guest";
If number is null, result is set to 10.
C Sharp (C#)
int? number = null;
int result = number ?? 10;
Since input is not null, output will be "Hello".
C Sharp (C#)
string input = "Hello";
string output = input ?? "Default";
Sample Program

This program shows how the null-coalescing operator picks a default value when the original is null, and uses the original when it is not null.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        string userName = null;
        string displayName = userName ?? "Anonymous";
        Console.WriteLine($"Hello, {displayName}!");

        int? userAge = null;
        int age = userAge ?? 18;
        Console.WriteLine($"Age: {age}");

        userName = "Alice";
        displayName = userName ?? "Anonymous";
        Console.WriteLine($"Hello, {displayName}!");
    }
}
OutputSuccess
Important Notes

The null-coalescing operator only checks for null, not other empty values like empty strings.

You can chain multiple ?? operators to check several values in order.

Summary

The null-coalescing operator ?? helps pick a fallback value when something is null.

It makes code shorter and easier to read when handling optional or missing data.

Use it to avoid long if-else checks for null values.