Null handling in C#: operators and nullable types
Missing data is normal in business code: an order that has not shipped has no ship date, a guest checkout has no customer email, and a lookup can fail. This page covers the C# features that let you say “this value may be absent” in the type system and then handle that absence without a wall of if (x != null) checks. It moves from the types (nullable value types and nullable reference types) to the operators that read, default and assign through possibly-null values.
Every complete sample is a file-based program: save it as sample.cs and run dotnet run sample.cs with the .NET 10 SDK (C# 14). All samples on this page were compiled and run with .NET SDK 10.0.115.
Features on this page
Section titled “Features on this page”| Feature | Version | Use it when |
|---|---|---|
| Nullable value types | C# 2 | A number, date or bool can genuinely be “not set”. |
| Nullable reference types | C# 8 | You want the compiler to warn before a null dereference happens. |
| Null-conditional operator | C# 6 | You read a member or element through a reference that may be null. |
| Null-coalescing operator | C# 2 | You need a fallback value when an expression is null. |
| Null-coalescing assignment | C# 8 | You initialize a field or variable only if it is still null. |
| Null-conditional assignment | C# 14 | You set a member only when its owner exists. |
Nullable value types
Section titled “Nullable value types”Introduced in C# 2 (.NET Framework 2.0). A nullable value type T? is shorthand for System.Nullable<T>: a struct that holds a T plus a HasValue flag. It lets int, decimal, DateOnly or an enum say “no value” without a magic sentinel such as -1 or DateTime.MinValue, which are easy to forget and easy to mistake for real data.
Read the value safely with a pattern (if (shippedOn is DateOnly date)), with GetValueOrDefault(), or with ??. Reading .Value when HasValue is false throws InvalidOperationException. Arithmetic and comparison operators are lifted: if either operand is null, + returns null and <, >, <=, >= all return false. Equality is different: null == null is true.
Order[] orders =[ new(1001, ShippedOn: new DateOnly(2026, 11, 2), DiscountPercent: 10), new(1002, ShippedOn: null, DiscountPercent: null),];
foreach (Order order in orders){ string shipped = order.ShippedOn is DateOnly date ? date.ToString("yyyy-MM-dd") : "not shipped"; int discount = order.DiscountPercent.GetValueOrDefault(); Console.WriteLine($"Order {order.Id}: {shipped}, discount {discount}%");}
int? stored = null;int? requested = 5;Console.WriteLine($"stored + requested = {(stored + requested)?.ToString() ?? "null"}");Console.WriteLine($"stored < requested: {stored < requested}, stored >= requested: {stored >= requested}");
record Order(int Id, DateOnly? ShippedOn, int? DiscountPercent);Output:
Order 1001: 2026-11-02, discount 10%Order 1002: not shipped, discount 0%stored + requested = nullstored < requested: False, stored >= requested: FalsePitfalls:
- Lifted comparisons are both false.
stored < requestedandstored >= requestedare bothfalsewhen one side is null, soif (!(a < b))is not the same asif (a >= b). .Valuethrows. Prefer a pattern orGetValueOrDefault()overHasValueplus.Value.- Boxing drops the wrapper. A boxed
int?with no value becomes a plainnullreference, and a boxedint?with a value becomes a boxedint.
Nullable reference types
Section titled “Nullable reference types”Introduced in C# 8 (.NET Core 3.0). Reference types could always be null; this feature changes what the compiler knows. With the nullable context enabled (<Nullable>enable</Nullable>, on by default in project templates since .NET 6), string means “should never be null” and string? means “may be null”. Flow analysis then tracks each variable’s null state and warns, for example CS8602 “Dereference of a possibly null reference”, before the code runs.
It is a compile-time feature only: annotations add no runtime checks, and a non-nullable parameter can still receive null from older or unannotated code. That is why public APIs still validate arguments. Attributes from System.Diagnostics.CodeAnalysis describe contracts the annotations alone cannot, such as [NotNullWhen(true)] on a Try... method’s out parameter.
#nullable enableusing System.Diagnostics.CodeAnalysis;
var directory = new CustomerDirectory();directory.Add(new Customer("C-1", "Ada Lopez", Email: null));directory.Add(new Customer("C-2", "Ben Ortiz", Email: "ben@example.test"));
foreach (string id in new[] { "C-1", "C-2", "C-9" }){ if (directory.TryFind(id, out Customer? customer)) { // [NotNullWhen(true)] tells the compiler customer is not null here. string contact = customer.Email ?? "(no email on file)"; Console.WriteLine($"{id} {customer.Name}: {contact}"); } else { Console.WriteLine($"{id}: not found"); }}
record Customer(string Id, string Name, string? Email);
class CustomerDirectory{ private readonly Dictionary<string, Customer> _byId = new();
public void Add(Customer customer) => _byId[customer.Id] = customer;
public bool TryFind(string id, [NotNullWhen(true)] out Customer? customer) => _byId.TryGetValue(id, out customer);}Output:
C-1 Ada Lopez: (no email on file)C-2 Ben Ortiz: ben@example.testC-9: not foundWriting Console.WriteLine(customer.Email.Length); instead produces warning CS8602: Dereference of a possibly null reference. at compile time, and a NullReferenceException at run time if you ignore it.
Pitfalls:
- Warnings are not guarantees. Deserializers, reflection and unannotated libraries can still hand you null in a non-nullable property.
- The
!operator only silences the compiler.name!.Lengthstill throws ifnameis null; use it only where you can prove the value is set. - Enable it project-wide. Mixing enabled and disabled files produces “oblivious” types that hide real problems. For a large migration, enable per project and treat the warnings as a work list.
Null-conditional operator
Section titled “Null-conditional operator”Introduced in C# 6 (.NET Framework 4.6). a?.Member and a?[index] evaluate the member or element only when a is not null; otherwise the whole expression is null. The operator short-circuits: in order?.Customer.Address, if order is null nothing to its right runs. Use ?. again at each link that can itself be null.
Because the chain can stop, the result type is lifted: missing?.Lines.Count is int?, not int. Pair it with ?? to get back to a non-nullable value. The operator evaluates its left operand only once, which makes Handler?.Invoke(args) the standard thread-safe way to raise an event or call an optional delegate.
var orders = new Dictionary<int, Order>{ [1001] = new(1001, new Customer("Ada Lopez", new Address("Lisbon")), [new("SKU-RED-01", 2)]), [1002] = new(1002, new Customer("Ben Ortiz", Address: null), []),};
Order? found = Find(1001);Order? noAddress = Find(1002);Order? missing = Find(9999);
Console.WriteLine(found?.Customer?.Address?.City ?? "Unknown city");Console.WriteLine(noAddress?.Customer?.Address?.City ?? "Unknown city");Console.WriteLine(missing?.Customer?.Address?.City ?? "Unknown city");
int? lineCount = missing?.Lines.Count; // int? because the chain can stopConsole.WriteLine($"Lines on 9999: {lineCount?.ToString() ?? "n/a"}");Console.WriteLine($"First SKU on 1001: {found?.Lines?[0].Sku}");
if (found is not null){ found.Shipped = id => Console.WriteLine($"Order {id} shipped");}found?.MarkShipped();missing?.MarkShipped(); // nothing happens
Order? Find(int id) => orders.GetValueOrDefault(id);
record Address(string City);record Customer(string Name, Address? Address);record OrderLine(string Sku, int Quantity);
class Order(int id, Customer? customer, List<OrderLine> lines){ public int Id { get; } = id; public Customer? Customer { get; } = customer; public List<OrderLine> Lines { get; } = lines; public Action<int>? Shipped { get; set; }
// Copies the delegate reference once, so another thread can't null it between check and call. public void MarkShipped() => Shipped?.Invoke(Id);}Output:
LisbonUnknown cityUnknown cityLines on 9999: n/aFirst SKU on 1001: SKU-RED-01Order 1001 shippedPitfalls:
?[]does not protect the index.found?.Lines?[0]still throwsArgumentOutOfRangeExceptionon an empty list; it only guards against a null list.- Lifted comparisons.
numbers?.Length < 2isfalsewhennumbersis null, which may not be what the check intended. Add?? 0first. - Do not hide bugs. If a value should never be null at that point,
?.turns a fast failure into silently missing data.
Null-coalescing operator
Section titled “Null-coalescing operator”Introduced in C# 2 (.NET Framework 2.0). a ?? b returns a if it is not null and otherwise evaluates and returns b. The right side is evaluated only when needed, so it can be an expensive call. The operator is right-associative, so a ?? b ?? c returns the first non-null value, which reads naturally for layered settings such as “order override, then customer preference, then system default”.
When the left side is a nullable value type and the right side is the underlying type, the result is the non-nullable type: int? ?? int gives int. Since C# 7.0 the right side can be a throw expression, which turns argument validation into a single expression.
string? orderOverride = null;string? customerCurrency = "EUR";string currency = orderOverride ?? customerCurrency ?? "USD";Console.WriteLine($"Currency: {currency}");
int? requestedQuantity = null;int quantity = requestedQuantity ?? 1; // int? ?? int gives intConsole.WriteLine($"Quantity: {quantity}");
string? deliveryNote = "";Console.WriteLine($"Note via ??: '{deliveryNote ?? "(none)"}'");Console.WriteLine($"Note via IsNullOrWhiteSpace: '{(string.IsNullOrWhiteSpace(deliveryNote) ? "(none)" : deliveryNote)}'");
try{ Reserve(sku: null);}catch (ArgumentNullException ex){ Console.WriteLine(ex.Message);}
static string Reserve(string? sku) => "Reserved " + (sku ?? throw new ArgumentNullException(nameof(sku)));Output:
Currency: EURQuantity: 1Note via ??: ''Note via IsNullOrWhiteSpace: '(none)'Value cannot be null. (Parameter 'sku')Pitfalls:
- Null is not empty.
"",0and an empty list are not null, so??keeps them. Usestring.IsNullOrWhiteSpacewhen blank input should also fall back. - Precedence.
??binds more loosely than+, so"Total: " + amount ?? "n/a"groups as("Total: " + amount) ?? "n/a". Add parentheses. - Not overloadable. Types cannot customize
??; it always tests for null.
Null-coalescing assignment
Section titled “Null-coalescing assignment”Introduced in C# 8 (.NET Core 3.0). x ??= value assigns value to x only when x is null, and the whole expression returns the resulting value of x. The right side is not evaluated at all when x already has a value. That makes it the shortest correct form of “create on first use”: lazy lists, caches and settings objects that most instances never need.
The left side must be a variable, property or indexer, and the result can be used directly, as in (_notes ??= new()).Add(note).
var cart = new Cart();Console.WriteLine($"Notes before: {cart.NoteCount}");cart.AddNote("Leave at front desk");cart.AddNote("Gift wrap");Console.WriteLine($"Notes after: {cart.NoteCount} ({string.Join("; ", cart.Notes)})");Console.WriteLine($"Lists created: {Cart.ListsCreated}");
string? region = null;region ??= LookupRegion("from customer profile");region ??= LookupRegion("from IP address"); // not called: region already has a valueConsole.WriteLine($"Region: {region}");
static string LookupRegion(string source){ Console.WriteLine($" looking up region {source}"); return "EU-West";}
class Cart{ public static int ListsCreated; private List<string>? _notes;
public IReadOnlyList<string> Notes => _notes ?? []; public int NoteCount => _notes?.Count ?? 0;
public void AddNote(string note) => (_notes ??= CreateList()).Add(note);
private static List<string> CreateList() { ListsCreated++; return []; }}Output:
Notes before: 0Notes after: 2 (Leave at front desk; Gift wrap)Lists created: 1 looking up region from customer profileRegion: EU-WestPitfalls:
- Not thread-safe. Two threads can both see null and both create a value. Use
Lazy<T>orLazyInitializer.EnsureInitializedfor shared state. - Only null triggers it. An empty string or zero is kept, just as with
??.
Null-conditional assignment
Section titled “Null-conditional assignment”Introduced in C# 14 (.NET 10). The null-conditional operators ?. and ?[] can now appear on the left of an assignment or compound assignment: order?.Status = "Packed" assigns only when order is not null. In statement form it is equivalent to if (order is not null) order.Status = ..., except that order is evaluated once.
The important rule is that the right side is evaluated only when the receiver is not null, so none?.Status = NextStatus() never calls NextStatus. All compound assignments such as += and -= work; increment and decrement (++, --) do not (error CS1059). The expression is still not a variable, so it cannot be passed as ref or out or used in deconstruction.
Order? active = new(1001);Order? none = null;
active?.Status = NextStatus("Packed");none?.Status = NextStatus("Shipped"); // NextStatus is not called
active?.Charges["shipping"] += 4.99m; // compound assignment is allowednone?.Charges["shipping"] += 4.99m;
Dictionary<string, int>? metrics = null;metrics?["errors"] += 1; // no-op, no exception
Console.WriteLine($"Active: {active?.Status}, shipping {active?.Charges["shipping"]}");Console.WriteLine($"None: {none?.Status ?? "(no order)"}");
static string NextStatus(string status){ Console.WriteLine($" computing status {status}"); return status;}
class Order(int id){ public int Id { get; } = id; public string Status { get; set; } = "New"; public Dictionary<string, decimal> Charges { get; } = new() { ["shipping"] = 0m };}Output:
computing status PackedActive: Packed, shipping 4.99None: (no order)Pitfalls:
- Silent no-op. If a missing receiver is a bug, an explicit check that throws or logs is better than an assignment that quietly does nothing.
- Hidden side effects. Readers may not expect the right-hand call to be skipped; keep side-effecting calls out of these assignments.
- Reference receivers only, in practice. A receiver of nullable value type is not supported, because the value inside a
Nullable<T>is not a variable.
Choosing between them
Section titled “Choosing between them”- Model absence in the type first:
T?for value types,string?and friends for reference types with nullable context enabled. - To read through something that may be null, use
?.; to turn the result into a usable value, add??. - To create something on first use in single-threaded code, use
??=; for shared state, useLazy<T>. - To write through something that may be null, use
?.assignment (C# 14), but only where “do nothing” is the correct behavior. - When null means a bug, do not reach for any of these operators: validate and throw (
ArgumentNullException.ThrowIfNull).
Interview questions
Section titled “Interview questions”What is the difference between int? and string??
int? is a different runtime type, Nullable<int>, with HasValue and Value. string? is the same runtime type as string; the ? is only an annotation that the compiler’s flow analysis uses to issue warnings.
Does enabling nullable reference types stop NullReferenceException?
No. It produces compile-time warnings only. Values from deserialization, reflection, unannotated libraries or code using ! can still be null at run time, so public APIs should still validate inputs.
What does a?.B.C() do when a is null, and what is its type?
It short-circuits: neither B nor C() is evaluated and the result is null. If C() returns a value type T, the expression’s type is T?.
When is the right side of x ??= Create() evaluated?
Only when x is null. If x already has a value, Create() is not called. The same rule applies to ?? and to C# 14 null-conditional assignment.
Why does if (!(a < b)) behave differently from if (a >= b) for int??
Lifted comparison operators return false when either operand is null, so both a < b and a >= b are false. The negation of the first is true while the second is false.
Senior scenario: an OrdersPortal service has 2,000 nullable warnings after enabling the feature. How would you roll it out?
Enable it project by project, starting with leaf libraries such as domain models so callers inherit accurate annotations. Fix public API signatures first (? where null is valid, guard clauses where it is not), use [NotNullWhen] and [MemberNotNull] for patterns the compiler cannot infer, and avoid blanket !. Treat new warnings as errors (WarningsAsErrors for the nullable warnings) once a project is clean so it stays clean, and keep runtime validation at trust boundaries such as API controllers and message handlers.
Related pages
Section titled “Related pages”- Pattern matching in C#:
is null,is not nulland property patterns as null checks. - Object construction and initialization: required members and constructors that keep non-nullable properties set.
- C# 14 release guide: null-conditional assignment and the rest of the release.
- C# version history