C# nullable types
last modified November 6, 2026
In this article we show how to work with nullable types and null values in C#.
The null literal represents a missing value. Dereferencing a
null reference throws a NullReferenceException, one
of the most common errors in C# programs. Over the years, C# has gained
several features that help to avoid it.
C# has value types and reference types. Value types, such as
int or bool, cannot hold null on their
own. Reference types, such as string or classes, can.
- C# 2.0 added nullable value types;
int?is anintthat can also benull. - C# 8.0 added nullable reference types;
string?says that a variable may benull, whilestringsays it should not be. The compiler then warns about possible null dereferences.
Both use the same T? syntax, but they work differently.
int? is a different type, Nullable<int>.
string? is the same string type with an annotation
that exists only for the compiler.
Nullable context
The nullable context controls whether the compiler analyzes null states of
reference types. It is enabled in new projects by the Nullable
property of the project file.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
File-based apps, which are run with dotnet run file.cs, have
the nullable context enabled by default. The context can also be changed
for part of a file with the #nullable directive.
#nullable enable #nullable disable #nullable restore
Nullable value types
A nullable value type T? is shorthand for the
Nullable<T> struct. It holds a value of the underlying
type or null.
int? x = 5;
Nullable<int> y = null;
Console.WriteLine($"x: HasValue {x.HasValue}, Value {x.Value}");
Console.WriteLine($"y: HasValue {y.HasValue}");
Console.WriteLine($"y default: {y.GetValueOrDefault()}, {y.GetValueOrDefault(-1)}");
Console.WriteLine($"y is null: {y is null}, y == null: {y == null}");
try
{
int v = y.Value;
}
catch (InvalidOperationException e)
{
Console.WriteLine(e.Message);
}
int z = (int)x;
Console.WriteLine($"z: {z}");
int? and Nullable<int> are the same type.
Console.WriteLine($"x: HasValue {x.HasValue}, Value {x.Value}");
The HasValue property tells whether there is a value, and
Value returns it.
Console.WriteLine($"y default: {y.GetValueOrDefault()}, {y.GetValueOrDefault(-1)}");
GetValueOrDefault returns the value, or a default when there is
none: the default of the underlying type, or the given argument.
int v = y.Value;
Reading Value of an empty nullable throws
InvalidOperationException. The compiler warns about this line
with CS8629.
int z = (int)x;
An explicit cast also unwraps the value; it throws the same exception if there is none.
$ dotnet run x: HasValue True, Value 5 y: HasValue False y default: 0, -1 y is null: True, y == null: True Nullable object must have a value. z: 5
Lifted operators
The operators of a value type also work with its nullable version. These
lifted operators return null if an operand is
null.
int? a = 10;
int? b = null;
Console.WriteLine($"a + 5 = {a + 5}");
Console.WriteLine($"a + b = {a + b ?? -1}");
Console.WriteLine($"a > b: {a > b}, a <= b: {a <= b}");
Console.WriteLine($"b == null: {b == null}");
bool? yes = true;
bool? no = false;
bool? unknown = null;
Console.WriteLine($"unknown & no: {Show(unknown & no)}");
Console.WriteLine($"unknown & yes: {Show(unknown & yes)}");
Console.WriteLine($"unknown | yes: {Show(unknown | yes)}");
Console.WriteLine($"unknown | no: {Show(unknown | no)}");
static string Show(bool? v) => v?.ToString() ?? "null";
Adding null to a number gives null, which the
?? operator replaces with -1.
Console.WriteLine($"a > b: {a > b}, a <= b: {a <= b}");
The comparison operators return false when an operand is
null. Note that both a > b and
a <= b are false.
Console.WriteLine($"unknown & no: {Show(unknown & no)}");
For bool?, the & and | operators
use three-valued logic, where null means unknown. An unknown
value AND false is false, and an unknown value OR true is true, because the
result does not depend on the unknown value.
$ dotnet run a + 5 = 15 a + b = -1 a > b: False, a <= b: False b == null: True unknown & no: False unknown & yes: null unknown | yes: True unknown | no: null
Check for null
We can use the != and is not operators to check for
null values.
string?[] words = ["sky", "black", "rock", null, "rain", "cup"];
foreach (var word in words)
{
if (word != null)
{
Console.WriteLine($"{word} has {word.Length} letters");
}
}
Console.WriteLine("-------------------------");
foreach (var word in words)
{
if (word is not null)
{
Console.WriteLine($"{word.ToUpper()}");
}
}
We have an array of words, one of which is null. Before we
access a word's members, we check that it is not null.
if (word is not null)
The is not null pattern is preferred, because it cannot be
changed by an overloaded != operator.
$ dotnet run sky has 3 letters black has 5 letters rock has 4 letters rain has 4 letters cup has 3 letters ------------------------- SKY BLACK ROCK RAIN CUP
HasValue and patterns
A nullable value can be checked with HasValue or unwrapped with
a type pattern.
int?[] vals = [1, 2, 3, null, 4, 5];
int sum = 0;
int nulls = 0;
foreach (int? e in vals)
{
if (e.HasValue)
{
sum += e.Value;
}
else
{
nulls++;
}
}
Console.WriteLine($"The sum is: {sum}, nulls: {nulls}");
int product = 1;
foreach (int? e in vals)
{
if (e is int n)
{
product *= n;
}
}
Console.WriteLine($"The product is: {product}");
Console.WriteLine($"LINQ sum: {vals.Sum()}");
We calculate the sum of the values and count the nulls.
if (e is int n)
The type pattern checks for a value and assigns it to n in one
step.
Console.WriteLine($"LINQ sum: {vals.Sum()}");
LINQ's Sum for nullable numbers skips null
elements.
$ dotnet run The sum is: 15, nulls: 1 The product is: 120 LINQ sum: 15
Nullable reference types
In a nullable context, the compiler tracks whether a reference may be
null and reports warnings.
string? name = GetName(1);
Console.WriteLine(name.Length);
string city = GetName(2);
Console.WriteLine(city);
if (name is not null)
{
Console.WriteLine(name.ToUpper());
}
static string? GetName(int id) => id == 1 ? "Peter" : null;
GetName returns string?, so the result may be
null.
string? name = GetName(1); Console.WriteLine(name.Length);
Accessing Length without a check produces warning CS8602.
string city = GetName(2);
Assigning a possibly null value to a non-nullable string
variable produces warning CS8600.
if (name is not null)
{
Console.WriteLine(name.ToUpper());
}
After the null check, the compiler knows that name is not
null, so there is no warning inside the block. The warnings do
not stop the program from compiling; they point to places where a
NullReferenceException could occur.
$ dotnet build warnings.cs warnings.cs(2,19): warning CS8602: Dereference of a possibly null reference. warnings.cs(4,15): warning CS8600: Converting null literal or possible null value to non-nullable type.
Null-conditional operators
The null-conditional operators ?. and ?[] apply a
member access or an element access only if the operand is not
null; otherwise the result is null.
List<User?> users =
[
new("John Doe", "gardener"),
new(null, null),
null,
new("Lucia Newton", "teacher")
];
foreach (User? user in users)
{
string? name = user?.Name?.ToUpper();
int? len = user?.Name?.Length;
Console.WriteLine($"{name ?? "-"} {len}");
}
int[]? vals = null;
Console.WriteLine($"First: {vals?[0]}");
vals = [3, 4, 5];
Console.WriteLine($"First: {vals?[0]}");
record User(string? Name, string? Occupation);
The list contains a user with null properties and a null user.
string? name = user?.Name?.ToUpper(); int? len = user?.Name?.Length;
If user or its Name is null, the
whole chain short-circuits and returns null; neither
ToUpper nor Length is evaluated. Since
Length is an int, the result type of the chain is
int?.
Console.WriteLine($"First: {vals?[0]}");
The ?[] operator accesses an element only if the array or
collection is not null. It does not protect against an index
that is out of range.
$ dotnet run JOHN DOE 8 - - LUCIA NEWTON 12 First: First: 3
Null-conditional assignment
Since C# 14, the null-conditional operators can appear on the left side of an assignment.
Customer? c1 = new() { Name = "Paul" };
Customer? c2 = null;
c1?.Order = GetOrder("c1");
c2?.Order = GetOrder("c2");
Console.WriteLine($"c1 order: {c1?.Order}");
Console.WriteLine($"c2 order: {c2?.Order ?? "none"}");
static string GetOrder(string who)
{
Console.WriteLine($"GetOrder called for {who}");
return "laptop";
}
class Customer
{
public string? Name { get; set; }
public string? Order { get; set; }
}
The property is assigned only if the object is not null.
c2?.Order = GetOrder("c2");
Because c2 is null, the right side is not
evaluated: GetOrder is called only once, for c1.
Before C# 14, we had to write if (c2 is not null) c2.Order = ....
$ dotnet run GetOrder called for c1 c1 order: laptop c2 order: none
ArgumentNullException
The ArgumentNullException is thrown when a null
argument is passed to a method that does not accept it.
List<string?> words = ["falcon", null, "water", "war", "fly", "wood", "wrath"];
foreach (string? word in words)
{
try
{
int n = CountLetter(word, 'w');
Console.WriteLine($"{word}: {n}");
}
catch (ArgumentNullException e)
{
Console.WriteLine(e.Message);
}
}
static int CountLetter(string? word, char c)
{
ArgumentNullException.ThrowIfNull(word);
return word.Count(e => e == c);
}
The method counts the occurrences of a letter in a word.
ArgumentNullException.ThrowIfNull(word);
ThrowIfNull throws ArgumentNullException if the
argument is null. The parameter name in the message is filled in
automatically. After the call, the compiler knows that word is
not null.
$ dotnet run falcon: 0 Value cannot be null. (Parameter 'word') water: 1 war: 1 fly: 0 wood: 1 wrath: 1
Null-forgiving operator
The null-forgiving operator ! tells the compiler that an
expression is not null, which suppresses the warning. It has no
effect at run time.
var stock = new Dictionary<string, int> { ["apples"] = 12, ["pears"] = 0 };
string product = FindProduct(stock, "apples")!;
Console.WriteLine($"{product}: {product.Length} characters");
string missing = FindProduct(stock, "plums")!;
try
{
Console.WriteLine(missing.Length);
}
catch (NullReferenceException e)
{
Console.WriteLine(e.GetType().Name);
}
static string? FindProduct(Dictionary<string, int> stock, string name) =>
stock.ContainsKey(name) ? name : null;
FindProduct returns string?. Without the
! operator, assigning the result to a string
variable would produce warning CS8600.
string missing = FindProduct(stock, "plums")!;
If we are wrong, the operator does not help. The variable holds
null, and accessing Length throws a
NullReferenceException. Use ! only when you know
more than the compiler, for example after a check it cannot see.
$ dotnet run apples: 6 characters NullReferenceException
Null-coalescing operator
The null-coalescing operator ?? returns its left operand if it
is not null; otherwise, it evaluates and returns the right
operand.
List<string?> words = ["work", "falcon", null, "cloud", null];
foreach (string? word in words)
{
string e = word ?? "null value";
Console.WriteLine(e);
}
int? limit = null;
int max = limit ?? 100;
Console.WriteLine($"max: {max}");
string? input = null;
try
{
string val = input ?? throw new ArgumentException("input is required");
}
catch (ArgumentException e)
{
Console.WriteLine(e.Message);
}
We print "null value" instead of an empty line for null words.
int max = limit ?? 100;
With a nullable value type, ?? gives a non-nullable result with
a default value.
string val = input ?? throw new ArgumentException("input is required");
The right operand can be a throw expression, which validates a value in one line.
$ dotnet run work falcon null value cloud null value max: 100 input is required
Null-coalescing assignment
The null-coalescing assignment operator ??= assigns the right
operand to the left operand only if the left operand is null.
List<int>? vals = null;
vals ??= [1, 2, 3, 4, 5];
vals.Add(6);
vals.Add(7);
vals.Add(8);
Console.WriteLine(string.Join(", ", vals));
vals ??= [1, 2, 3, 4, 5];
Console.WriteLine(string.Join(", ", vals));
First, the variable is null.
vals ??= [1, 2, 3, 4, 5];
Since vals is null, the new list is assigned. We
then add three values to it. The second ??= does nothing,
because vals is no longer null.
$ dotnet run 1, 2, 3, 4, 5, 6, 7, 8 1, 2, 3, 4, 5, 6, 7, 8
IsNullOrEmpty and IsNullOrWhiteSpace
The string.IsNullOrEmpty method checks whether a string is
null or empty. string.IsNullOrWhiteSpace also
returns true for strings that contain only white-space
characters.
string?[] words = ["\t", "falcon", " ", null, "\n", "cloud", ""];
Console.WriteLine($"{"value",-10} {"IsNullOrEmpty",-14} IsNullOrWhiteSpace");
foreach (string? e in words)
{
string shown = e is null ? "null" : $"\"{e.Replace("\t", "\\t").Replace("\n", "\\n")}\"";
Console.WriteLine($"{shown,-10} {string.IsNullOrEmpty(e),-14} {string.IsNullOrWhiteSpace(e)}");
}
We apply both methods to strings with tabs, spaces, and newlines. The tab and newline characters are shown as escape sequences.
Console.WriteLine($"{shown,-10} {string.IsNullOrEmpty(e),-14} {string.IsNullOrWhiteSpace(e)}");
Only null and the empty string are null or empty. Strings with
spaces, tabs, or newlines are null or white space.
$ dotnet run value IsNullOrEmpty IsNullOrWhiteSpace "\t" False True "falcon" False False " " False True null True True "\n" False True "cloud" False False "" True True
Source
In this article we have worked with nullable types in C#.
Author
List all C# tutorials.