The null-conditional operator helps you safely access members or elements of an object that might be null, avoiding errors.
Null-conditional operator in 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.
Name from person. If person is null, name becomes null instead of crashing.Person person = null;
string name = person?.Name;person and Name are not null.int? length = person?.Name?.Length;FirstOrDefault() on list only if list is not null.var firstItem = list?.FirstOrDefault();
int? value = dictionary?["key"];
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.
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); } }
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.
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.