Skip to content

1.15 — Nullable Value Types and Nullable Reference Types

← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.14 Extension methods · Next: 1.16 Null operators

Markers: 🔥 ⚠️ · Confidence: 🔴 · Last reviewed: —


TL;DR

  • Nullable value types (int?) are real. They are a struct that wraps a value plus a "has it got one?" flag.
  • Nullable reference types (string?) are not real. They are compiler warnings only. Nothing changes at runtime.
  • That difference is the whole interview question. string? and string compile to exactly the same thing.

The concept

These two features look similar and work completely differently. Understanding why is the point of this topic.

Nullable value types solve a genuine problem. An int cannot be null — it always holds a number. But sometimes you need "no value": a database column that allows NULL, an optional form field. So .NET provides int?, which is really Nullable<int> — a small struct holding an int plus a bool saying whether it is set.

Nullable reference types solve a different problem. A string could always be null, and the compiler never warned you. So C# 8 added a way to say "this one should never be null, warn me if I might be breaking that."

The critical difference:

Nullable value types Nullable reference types
Since C# 2 (2005) C# 8 (2019)
Real at runtime? Yes — a different type No — compiler warnings only
Enforced? Yes, by the type system No, nothing at runtime

How it works

Nullable value types — real

int? age = null;         // really Nullable<int>
int? score = 42;

age.HasValue;            // false
score.HasValue;          // true
score.Value;             // 42 — throws InvalidOperationException if null

int definite = score ?? 0;                 // 42
int fromNull = age ?? 0;                   // 0

if (score is int actualScore)              // pattern matching unwraps it
    Console.WriteLine(actualScore * 2);

Because it is a real type, the compiler genuinely stops you doing unsafe things:

int? maybe = null;
int definite = maybe;      // COMPILE ERROR — no automatic conversion
int definite = maybe.Value;  // compiles, but THROWS at runtime if null

Nullable reference types — just warnings

Turn it on in your .csproj (this is the default in new .NET projects):

<Nullable>enable</Nullable>

Now the meaning of your declarations changes:

string name = "Ada";       // "I promise this is never null"
string? nickname = null;   // "this might be null"

The compiler now tracks this and warns you:

string name = null;
// WARNING CS8600: Converting null literal to non-nullable type

string? nickname = GetNickname();
Console.WriteLine(nickname.Length);
// WARNING CS8602: Dereference of a possibly null reference

But watch this:

string? a = null;
string  b = null!;      // the ! silences the warning

// Both of these are just "null" at runtime. Identical.
// The generated code is byte-for-byte the same.

There is no runtime check. If null arrives from somewhere the compiler could not see — JSON deserialization, a database, reflection, or older code compiled without the feature — it flows straight through and you get a NullReferenceException exactly as before.

So the honest summary is: nullable reference types are a very good linting tool, not a guarantee. Saying that in an interview shows you actually understand the feature rather than having read the headline.

The null-forgiving operator !

! tells the compiler "trust me, this is not null":

var user = _users.FirstOrDefault(u => u.Id == id)!;   // I know it exists

It suppresses the warning and does absolutely nothing else. No check, no exception. If you are wrong, you get a NullReferenceException later at a more confusing place.

Treat every ! as a small piece of technical debt. Sometimes it is genuinely correct — when you know something the compiler cannot — but if a file is full of them, the annotations are wrong somewhere.

Where null still gets in

The compiler analyses your code. It cannot analyse the outside world.

public class Person
{
    public string Name { get; set; }    // declared non-nullable
}

var p = JsonSerializer.Deserialize<Person>("{}");
Console.WriteLine(p.Name.Length);
// Name is NULL at runtime. No warning was given.
// The deserializer set fields directly and ignored your annotation.

The same applies to Entity Framework materialising entities, reflection, and any library compiled before nullable reference types existed.

The practical rule: annotations are documentation and a safety net inside your own code. At the boundaries — HTTP input, database rows, external APIs — you still need real validation. See 11.4.

Making it useful

For properties, combine with required so the compiler actually enforces initialisation:

public class Person
{
    public required string Name { get; init; }   // must be set — compile error if not
    public string? Nickname { get; init; }       // genuinely optional
}

Without required, a non-nullable property produces a warning at the declaration and then everyone ignores it. With required, forgetting it is a hard error at the call site.


Code

A realistic method showing the annotations doing real work:

public async Task<OrderDto?> GetOrderAsync(Guid id, CancellationToken ct)
{
    var order = await _db.Orders
        .Include(o => o.Customer)
        .FirstOrDefaultAsync(o => o.Id == id, ct);

    // The '?' on the return type tells callers: this can be null.
    // The compiler will warn them if they forget to check.
    if (order is null) return null;

    return new OrderDto
    {
        Id = order.Id,
        // Customer is a navigation property — could be null if Include failed
        CustomerName = order.Customer?.Name ?? "(unknown)",
        Total = order.Total
    };
}

And the caller — the compiler now forces the check:

var dto = await GetOrderAsync(id, ct);

Console.WriteLine(dto.Total);
// WARNING — dto might be null, you did not check

if (dto is not null)
    Console.WriteLine(dto.Total);   // no warning — the compiler followed your check

That last part is the real value. The compiler tracks the flow of your code. Once you check for null, it knows the variable is safe for the rest of that branch.


Interview questions

Q: What is the difference between a nullable value type and a nullable reference type?

A nullable value type like int? is real — it is Nullable<int>, a struct that holds the value plus a flag saying whether it is set. The type system genuinely enforces it, so you cannot assign an int? to an int without handling the null case. A nullable reference type like string? is not real at all. It is purely a compile-time annotation that turns on warnings. At runtime string? and string are the exact same type and produce identical code. So one is a type-system feature, and the other is a static analysis feature wearing similar syntax.

Q: Do nullable reference types prevent null reference exceptions?

No, and this is the most important thing to understand about them. They help you find places where null might flow, and if you fix every warning your own code becomes much safer. But nothing is checked at runtime. Null can still arrive from JSON deserialization, from Entity Framework, from reflection, or from a library compiled without the feature — and none of those respect your annotations. So they are an excellent linting tool, not a guarantee. You still need real validation at your application's boundaries.

Q: What does the ! operator do?

It is the null-forgiving operator. It tells the compiler "I know this looks like it could be null, but trust me, it is not" and suppresses the warning. It generates no code and performs no check. It is sometimes legitimately needed when you know something the compiler's flow analysis cannot work out, but each use is a small piece of debt. A file full of them usually means the annotations are wrong somewhere rather than that the compiler is being unhelpful.

Q: How do you handle nullability on an API model?

I mark genuinely optional properties as nullable and mandatory ones as non-nullable and required, so forgetting one is a compile error rather than a runtime surprise. But I do not rely on that for incoming HTTP data, because model binding and deserialization can bypass it. For real input I use validation attributes or FluentValidation, so a missing field produces a proper 400 response with a clear message rather than a null reference exception deep in the handler.


Traps ⚠️

  • Nullable reference types are compile-time only. They enforce nothing at runtime.
  • Deserialization ignores them completely. JsonSerializer will happily leave a non-nullable property null and never warn you.
  • ! hides the problem rather than fixing it. It moves the crash somewhere less obvious.
  • A non-nullable property without required or an initialiser gives a warning where it is declared, which people learn to ignore, rather than an error where it matters.
  • int? cannot be assigned to int without handling null. .Value throws InvalidOperationException — note, not NullReferenceException — if there is no value.
  • Nullable<T> cannot be nested. There is no int??.
  • Turning <Nullable>enable</Nullable> on in an existing project produces hundreds of warnings. Enable it per-file with #nullable enable and work through gradually.


Sources