TExcelTAD
Home › C# › C# Nullable Types

C# Nullable Types

null means "no value". It is useful — a customer may have no middle name, a search may find nothing — but it is also the source of the most common runtime error in C#: the NullReferenceException. C# gives you tools on two levels: nullable value types and nullable reference types, plus a set of operators that make working with null safe and short.

Nullable value types: int?, double?, bool?

Value types such as int or bool cannot normally be null. Add a ? to the type to allow it. int? is shorthand for Nullable<int>.

csharp · try it yourself
using System;

int? age = null;
Console.WriteLine(age.HasValue);
Console.WriteLine(age == null);

age = 42;
Console.WriteLine(age.HasValue);
Console.WriteLine(age.Value);
Console.WriteLine(age.GetValueOrDefault());

double? discount = null;
Console.WriteLine(discount.GetValueOrDefault());
Console.WriteLine(discount.GetValueOrDefault(0.05));
False
True
True
42
42
0
0.05

Reading .Value when there is no value throws an InvalidOperationException. Arithmetic with null "lifts": null + 5 is null.

csharp · try it yourself
using System;

int? a = 10;
int? b = null;

Console.WriteLine(a + 5);
Console.WriteLine(b + 5 == null);
Console.WriteLine(a > b);         // comparisons with null are false

bool? answered = null;            // three states: yes, no, unknown
Console.WriteLine(answered switch
{
    true => "yes",
    false => "no",
    null => "not answered"
});
15
True
False
not answered

The null operators

Operator Name Meaning
x ?? y null-coalescing x if it is not null, otherwise y
x ??= y null-coalescing assignment assign y to x only if x is null
x?.Member null-conditional null if x is null, otherwise x.Member
x?[i] null-conditional index null if x is null, otherwise x[i]
x! null-forgiving tell the compiler "I know this is not null"
csharp · try it yourself
using System;

string nickname = null;
string display = nickname ?? "Guest";
Console.WriteLine(display);

string[] tags = null;
Console.WriteLine(tags?.Length);           // prints an empty line
Console.WriteLine(tags?.Length ?? 0);

Customer c = new Customer { Name = "Lea" };
Console.WriteLine(c.Address?.City ?? "no city");

c.Address = new Address { City = "Vienna" };
Console.WriteLine(c.Address?.City.ToUpper());

int? cached = null;
cached ??= 100;
cached ??= 200;
Console.WriteLine(cached);

class Customer
{
    public string Name;
    public Address Address;
}

class Address
{
    public string City;
}
Guest

0
no city
VIENNA
100

The ?. operator short-circuits the whole chain: if c.Address is null, then .City and .ToUpper() are not evaluated at all.

Nullable reference types

Reference types (string, arrays, classes) can always hold null at run time. Since C# 8, you can turn on nullable reference types so that the compiler tracks which references may be null. With the feature enabled:

  • string means "never null" and string? means "may be null".
  • The compiler warns when you dereference a string? without checking it, or assign null to a string.

New .NET projects enable this in the project file (<Nullable>enable</Nullable>). In a single file you can turn it on with a directive:

csharp · try it yourself
#nullable enable
using System;

static int CountVowels(string? text)
{
    if (text is null)        // after this check the compiler knows text is not null
        return 0;

    int count = 0;
    foreach (char ch in text.ToLower())
        if ("aeiou".Contains(ch)) count++;
    return count;
}

static string Initials(string first, string? middle, string last)
{
    string m = middle is { Length: > 0 } ? 
quot;{middle[0]}." : ""; return
quot;{first[0]}.{m}{last[0]}."; } Console.WriteLine(CountVowels("Nullable")); Console.WriteLine(CountVowels(null)); Console.WriteLine(Initials("John", "Ronald", "Tolkien")); Console.WriteLine(Initials("Ada", null, "Lovelace"));
3
0
J.R.T.
A.L.

Had we written text.ToLower() without the null check, the compiler would report warning CS8602: Dereference of a possibly null reference. The warnings do not change how the program runs — they are a safety net that catches mistakes before your users do.

Checking for null

Check Notes
x is null / x is not null Preferred — cannot be fooled by an overloaded ==
x == null Works, common in older code
ArgumentNullException.ThrowIfNull(x) Guard clause at the top of a method
x is { } value Not null, and binds it to a new variable

Tip: Use ! (null-forgiving) sparingly. It only silences the compiler; if you are wrong, you still get a NullReferenceException at run time.

Test yourself

What does int? x = null; Console.WriteLine(x ?? -1); print?

  1. null
  2. 0
  3. -1
  4. Nothing

What is the value of person?.Name when person is null?

  1. An empty string
  2. null
  3. It throws NullReferenceException
  4. "null"

With nullable reference types enabled, what does string? mean?

  1. A string that can never be null
  2. A string that may be null
  3. An optional parameter
  4. A nullable char