Nullable Reference Types in C#
Last Updated :
23 Oct, 2025
A nullable reference type, introduced in C# 8, is a reference type that is explicitly allowed to hold null. In contrast, a non-nullable reference type cannot hold null without generating compiler warnings. The feature relies on static code analysis rather than runtime enforcement.
Enabling Nullable Reference Types
Nullable reference types are not enabled by default in existing projects. They can be enabled using:
#nullable enable
or by adding the following to the project file:
<Nullable>enable</Nullable>
Once enabled, the compiler starts analyzing all reference types in the code for null safety.
Syntax
C#
#nullable enable
string nonNullableName = "Alice"; // Cannot be null
string? nullableName = null; // Can be null
- Nullable reference type: Add ? after the type.
- Non-nullable reference type: Omit ?.
Key Characteristics
- Compiler Warnings: Assigning null to a non-nullable reference triggers a compiler warning.
- Static Analysis: The compiler analyzes method parameters, return values and assignments to detect potential null dereferences.
- Optional Use: Nullable reference types are opt-in and can be applied selectively in projects.
- Runtime Behavior: No runtime enforcement; null assignments to non-nullable references are still possible but discouraged.
Example
C#
#nullable enable
public class User
{
public string Name { get; set; } // Non-nullable
public string? Email { get; set; } // Nullable
}
var user = new User();
user.Name = "John"; // OK
user.Email = null; // OK
user.Name = null; // Compiler warning
Nullable Reference Type in Methods
C#
string GetUserEmail(User user)
{
return user.Email; // Compiler warning: possible null reference
}
string GetUserName(User user)
{
return user.Name; // No warning: non-nullable
}
- The compiler warns if a nullable reference type might be dereferenced without null-checking.
Null-Forgiving Operator !
Sometimes, you know a nullable reference will not be null even if the compiler cannot infer it. In such cases, the null-forgiving operator (!) can be used:
C#
string? maybeName = GetName();
string name = maybeName!; // Suppresses compiler warning
Best Practices
- Prefer non-nullable reference types for fields, properties and method returns unless null is a meaningful value.
- Use nullable reference types for optional data or fields that may not always have a value.
- Combine with null-coalescing (??) and null-conditional (?.) operators for safe code.
- Review compiler warnings and address them rather than suppressing with ! unless necessary.
Use Cases
- APIs where certain parameters should never be null.
- Domain models where some properties are optional.
- Data transfer objects (DTOs) with optional fields.
- Code bases being refactored to eliminate null reference exceptions.
Explore
Introduction
Fundamentals
Control Statements
OOP Concepts
Methods
Arrays
ArrayList
String
Tuple
Indexers