Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# Null Check: Syntax, Patterns, and Pitfalls

Learn how to check for null in C# using equality operators, pattern matching, nullable types, and null-conditional operators. Avoid common pitfalls with practical examples.

~6 min readC#
#C##Null Checking#Nullable Types#Pattern Matching
A C# code snippet with a guard symbol representing null check patterns and nullable types.

Checking for null is one of the most frequent operations in C#. In modern C#, the direct checks are value is null and value is not null, but the language also provides equality operators, nullable type checks, null-conditional access, and null-coalescing operators. The right choice depends on the context, the type, and the behavior you want when a value is missing. This article covers the main syntaxes, explains how they behave at runtime, and highlights subtle differences that can lead to bugs if overlooked.

Null Checks with Equality Operators

The equality operator is a common way to write a null check:

csharp
if (value == null) { // handle null }

For reference types, this checks whether the reference points to no object. For nullable value types, comparing to null is equivalent to checking that HasValue is false. For non-nullable value types, the compiler rejects the comparison because they cannot be null.

csharp
int number = 42; if (number == null) // Compile error: operator cannot be applied { }

To compare a value type with null, you must use a nullable type:

csharp
int? maybeNumber = GetNumber(); if (maybeNumber == null) { // maybeNumber has no value }

The equality operator works, but it is not always the most expressive or safest choice, especially when overloaded operators are involved. A custom type can overload == to perform a custom comparison, which might not produce the intended null check. In that case, the is pattern is safer.

Nullable Value Types and HasValue

Nullable value types, declared with ? or Nullable<T>, have a HasValue property that indicates whether a value is present. You can check it directly:

csharp
int? count = GetCount(); if (count.HasValue) { int actual = count.Value; } else { // handle absence }

This is equivalent to count != null, but it makes the intent explicit. Accessing .Value when HasValue is false throws an InvalidOperationException. The null-coalescing operator ?? provides a safer way to extract a value:

csharp
int result = count ?? 0;

Using count.GetValueOrDefault() returns the underlying type's default value when the nullable has no value. The ?? operator lets you supply a different default explicitly.

Null-Conditional Operators (?.) and (?[])

The null-conditional operators allow you to access members or elements only when the receiver is not null. If the receiver is null, the entire expression evaluates to null, and the rest of the chain is skipped.

csharp
string? name = person?.Name; int? length = name?.Length;

Here, if person is null, name becomes null, and length also becomes null. This avoids writing multiple nested null checks. The same works for indexers:

csharp
string? first = list?[0];

If list is null, first is null. If list is not null but the index is out of range, an exception is thrown. The null-conditional operator only guards against a null receiver, not against other runtime errors.

These operators are particularly useful in expression chains where intermediate results can be null. They also work with value type properties, returning a nullable result:

csharp
int? age = person?.Age;

Because Age is an int, the result is int? to represent the possibility of a missing value.

Pattern Matching for Null Checks

C# 7 introduced pattern matching, and C# 9 added the not pattern. These provide a clear and safe way to check for null:

csharp
if (obj is null) { // handle null } if (obj is not null) { // handle non-null }

Unlike the == operator, the is null and is not null patterns cannot be overloaded and do not rely on custom equality logic. This makes them the recommended way to check for null in most modern C# code. For nullable value types, maybeNumber is null is true when HasValue is false.

You can also use property patterns to check nested properties without null-conditional operators:

csharp
if (person is { Address: { City: "London" } }) { // person is not null and has an Address with City "London" }

This pattern implicitly checks that person and person.Address are not null before comparing City. It is a concise alternative to a chain of null checks.

Null Coalescing and Null Coalescing Assignment

The null-coalescing operator ?? returns the left operand if it is not null; otherwise, it returns the right operand.

csharp
string displayName = name ?? "Unknown";

If name is null, displayName gets the string "Unknown". This works for both reference and nullable value types. The right operand is evaluated only when the left operand is null, which avoids unnecessary work.

The null-coalescing assignment operator ??= assigns the right operand to the left operand only if the left operand is null:

csharp
name ??= "Default";

This is equivalent to:

csharp
if (name is null) { name = "Default"; }

Both operators reduce the amount of boilerplate code needed for common null handling patterns. They are especially useful when initializing fields or properties lazily.

Null-Forgiving Operator (Postfix !)

The null-forgiving operator ! is a compile-time hint that tells the compiler a nullable expression is actually not null. It does not perform any runtime check. It is used to suppress nullable warnings when you are certain about the value.

csharp
string name = GetName()!;

If GetName() returns string?, the ! tells the compiler to treat it as string. If the value is actually null at runtime, using it later can throw a NullReferenceException. The operator is a promise to the compiler, not a safeguard.

Use it sparingly. Overusing ! can hide real nullability issues and make the code less safe. Prefer explicit null checks or null-conditional operators when the value might genuinely be null.

Performance and Maintainability Considerations

For reference types without a custom == overload, == null and is null are equivalent at runtime, and is not null is simply the inverse. These choices are readability and safety decisions, not meaningful performance decisions. Pattern matching is preferred because it avoids overloaded equality operators and makes the intent clear.

Null-conditional operators can add a small overhead because they insert a null check and a conditional branch. In most applications, this is negligible. However, in tight loops where the receiver is known to be non-null, a direct access may be faster. Profile before optimizing; the readability benefit usually outweighs micro-optimizations.

Nullable reference type annotations are a compile-time feature. They do not affect runtime behavior. They help you catch potential null dereferences during development, but they do not enforce null safety. A value declared as string? can still be null at runtime, and a value declared as string can be null if you use ! or ignore warnings.

When designing APIs, consider whether a method can return null and document it with nullable reference type annotations. This makes the contract explicit and helps callers decide which null check to use.

Common Pitfalls and Edge Cases

One subtle issue is the difference between == and is when a type overloads the equality operator. For example, a custom class might implement operator == to compare contents. In that case, obj == null can return an unexpected result if the overload does not handle null operands correctly. The is null pattern avoids overloaded operators, so it is safer.

For nullable value types, == is translated to a check on HasValue and, if both operands have values, a comparison of the underlying values. If the underlying type overloads ==, that overload is used. This can lead to unexpected behavior if the overload has side effects.

Another edge case is using ?? with a nullable value type and a default value that is not a constant. The right operand is evaluated lazily, which is useful for expensive computations. But be careful with side effects: they only run when the left operand is null.

Finally, remember that the null-forgiving operator does not change runtime behavior. It only suppresses warnings. If you use it to silence a warning without verifying the value, you may introduce a null dereference that is hard to trace. Always ensure the value is actually non-null at that point.

When working with collections, ?[] only guards against a null collection, not an index that is out of range. If you need to guard against both, combine it with a bounds check or use TryGetValue on dictionaries.

Understanding these nuances helps you write null checks that are correct, readable, and maintainable. Choose the syntax that best matches the intent: is null for a null check, HasValue for explicit nullable value type checks, ?. for safe member access, and ?? for providing defaults. Each has a specific role, and using them appropriately reduces bugs and makes the code easier to reason about.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.