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

Null-conditional operator in C Sharp (C#)

Choose your learning style9 modes available
Introduction

The null-conditional operator helps you safely access members or elements of an object that might be null, avoiding errors.

When you want to call a method on an object that might be null without causing a crash.
When you want to access a property of an object that could be missing (null).
When you want to check if an object is null before accessing its members in a simple way.
When you want to avoid writing multiple if-null checks in your code.
When you want to safely access elements in collections that might be null.
Syntax
C Sharp (C#)
object?.Member
object?[index]
object?.Method()

The ?. operator returns null if the object is null instead of throwing an error.

You can use it with properties, methods, and indexers.

Examples
This safely tries to get Name from person. If person is null, name becomes null instead of crashing.
C Sharp (C#)
Person person = null;
string name = person?.Name;
This safely gets the length of the name if both person and Name are not null.
C Sharp (C#)
int? length = person?.Name?.Length;
This calls FirstOrDefault() on list only if list is not null.
C Sharp (C#)
var firstItem = list?.FirstOrDefault();
This safely accesses the dictionary value for "key" if the dictionary is not null.
C Sharp (C#)
int? value = dictionary?["key"];
Sample Program

This program shows how the null-conditional operator ?. safely accesses the Name property. When person is null, it returns null instead of crashing. When person has a value, it prints the name.

C Sharp (C#)
using System;

class Person
{
    public string Name { get; set; }
}

class Program
{
    static void Main()
    {
        Person person = null;
        // Using null-conditional operator to safely get Name
        string name = person?.Name;

        if (name == null)
            Console.WriteLine("Name is null because person is null.");
        else
            Console.WriteLine(name);

        person = new Person { Name = "Alice" };
        // Now person is not null
        Console.WriteLine(person?.Name);
    }
}
OutputSuccess
Important Notes

The null-conditional operator helps avoid many if (obj != null) checks.

If the left side is null, the whole expression returns null immediately.

You can combine it with the null-coalescing operator ?? to provide default values.

Summary

The null-conditional operator ?. safely accesses members of objects that might be null.

It helps prevent errors by returning null instead of throwing exceptions.

Use it to write cleaner and safer code when dealing with nullable objects.