Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 182 ยท Variables and Types

Nullable Value Types

Learn C# nullable value types - int?, HasValue, Value, GetValueOrDefault, lifted operators, the ?? and ??= operators, null propagation and boxing of nullable values.

A value type such as int, bool or DateTime always holds a value. A new int is 0, a new bool is false, and there is no way to say "unknown" or "not provided". Real data is full of such gaps: a survey question the user skipped, an optional end date, a database column that allows NULL, a sensor that has not reported yet. Using 0 or -1 as a secret code for "missing" works until someone adds a real 0 to the data.

C# solves this with nullable value types. Write a question mark after the type (int?, bool?, DateTime?) and the variable can hold either a normal value or null. This lesson explains how that works under the hood, the properties and operators you use every day (HasValue, Value, ??, ??=, ?.), the "lifted" operators that make arithmetic with null behave sensibly, and what happens when a nullable is boxed.

Declaring and testing a nullable

int? is shorthand for Nullable<int>, a struct from the standard library that wraps your value together with a bool flag saying whether a value is present. It is still a value type: no heap allocation, and it copies like any other struct.

C# int? basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

You use .HasValue (or is null / is not null) to check, and .Value to read. The compiler can even see the problem in the example above and warns with CS8629 ("Nullable value type may be null") on the score.Value line; we keep it to show the exception. Reading .Value while the nullable is empty throws InvalidOperationException ("Nullable object must have a value."). A cast the other way around also exists: (int)score is the same as score.Value and throws in the same situation. The pattern bonus is int b is the tidiest way to test and unwrap at the same time.

Do not confuse nullable value types (int?, a struct that gets a null state) with nullable reference types (string?, an annotation that tells the compiler to check your null handling). They look alike, but one changes the runtime type and the other is a compile-time warning system. The second is covered in the Null Safety chapter, starting with Nullable Reference Types.

Giving null a default: GetValueOrDefault and ??

You rarely want to crash when a value is missing; you want a sensible fallback. There are two main tools.

  • GetValueOrDefault() returns the value, or the type's default (0 for int, false for bool) when empty. GetValueOrDefault(fallback) lets you choose the fallback.
  • The null-coalescing operator ?? returns the left side if it has a value, otherwise the right side. It is shorter and works for any nullable or reference type.
  • The null-coalescing assignment ??= assigns the right side only if the variable is currently null.
C# Fallbacks with ??, ??= and GetValueOrDefault

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The right side of ?? is evaluated lazily (only if needed), which makes ?? throw ... a neat way to say "this must have a value". There is a trap with GetValueOrDefault(): a missing value silently becomes 0, which may look exactly like real data. Choose a fallback that cannot be mistaken for real data, or keep the value nullable all the way to where you decide what "missing" means.

Lifted operators: arithmetic with nullables

For every operator that works on the underlying type, C# automatically provides a lifted version that works on the nullable type. The rule is simple: if either operand is null, the result is null (for arithmetic and most operators). It's like a spreadsheet cell that shows an error when it depends on an empty cell.

Comparison operators are slightly different. == and != treat two nulls as equal; <, >, <= and >= return false if either side is null.

C# Lifted operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The surprising line is a < b and a > b: both are false when one side is null, so you cannot assume that "not greater than" means "less than or equal to". When you sort or compare data that may contain nulls, decide explicitly where nulls go (first, last, excluded) instead of trusting the operators.

bool? and three-valued logic

bool? has three states: true, false and null ("unknown"). The logical operators & and | follow SQL-style three-valued logic: false & null is false (whatever the unknown is, the result is false) and true | null is true, but true & null is null.

C# bool? three-valued logic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Blank answers from a form or a database BIT NULL column are the classic use case for bool?.

Null propagation with value types

The null-conditional operator ?. short-circuits when its left side is null. When the result would be a value type, the whole expression becomes a nullable. This is how you safely read a member of an object that might not exist and keep going:

C# ?. with value types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The type of order?.Items.Length is int?, not int: the chain stops at the first null and produces null. Combined with ?? it is the compact way to write "this, or a default". C# 14 also lets you use ?. on the left of an assignment (order?.Count = 5), covered in the Null Safety chapter.

Boxing a nullable

Boxing converts a value type to object (it allocates a copy on the heap). Nullable types get special treatment:

  • A Nullable<int> with a value boxes to a plain boxed int.
  • A Nullable<int> without a value boxes to null, not to a box holding a "null int?".

This means a boxed nullable never has a runtime type of Nullable<T>. You can unbox a boxed int into either int or int?.

C# Boxing and the runtime type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

typeof(int?) prints System.Nullable1[System.Int32], and Nullable.GetUnderlyingTypegives you theintinside, which is handy in reflection and serialization code. Generic constraints matter too:where T : structacceptsintbut **not**int?, because Nullable` is itself not a "non-nullable value type".

Nullable types in practice

Typical places you meet nullable value types:

  • Optional data: DateTime? CancelledAt, decimal? Discount, int? Age.
  • Database mapping: a column that allows NULL maps to a nullable property (int?).
  • Parsing helpers: int? ParseOrNull(string s) => int.TryParse(s, out var n) ? n : null;
  • Tri-state flags: bool? for "yes / no / not answered".

A good rule of thumb: use nullable only when "no value" is a real, meaningful state. If a value is always required, keep it non-nullable and validate at the boundary. And prefer ??, ?. and pattern matching over repeated HasValue / Value pairs; they are shorter and cannot forget the check.

C# A nullable-returning parser

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does int? x = null; Console.WriteLine(x.Value); do?

    Reading Value on an empty nullable throws InvalidOperationException (Nullable object must have a value). Check HasValue first, or use ?? / GetValueOrDefault.
  2. 2. What is the value of int? a = 5; int? b = null; var r = a + b;?

    Lifted arithmetic operators return null when either operand is null.
  3. 3. Given int? a = 5; int? b = null;, what is a < b?

    Lifted relational operators (<, >, <=, >=) return false if either operand is null. That is why !(a < b) is not the same as a >= b.
  4. 4. What does int? x = null; x ??= 7; x ??= 9; leave in x?

    ??= assigns only when the variable is null. The first line assigns 7; the second finds a value already there and does nothing.
  5. 5. What is the result of boxing an int? that holds null into an object?

    An empty nullable boxes to a null reference; a nullable with a value boxes to a plain boxed int. A boxed nullable never has the runtime type Nullable<T>.

Summary

  • T? for a value type T is Nullable<T>: a struct holding the value plus a flag, so any value type can also be null.
  • Test with HasValue, is null / is not null or a pattern like x is int n; .Value throws on empty.
  • Use ?? for a fallback, ??= to assign only when empty, GetValueOrDefault(fallback) for a default, and ?? throw for required values.
  • Lifted operators give null when an operand is null; == treats two nulls as equal, but <, >, <= and >= return false with a null operand.
  • bool? uses three-valued logic; compare it with == true or use a switch expression instead of using it as a condition.
  • ?. on a member of value type produces a nullable (order?.Items.Length is int?).
  • An empty nullable boxes to null; a nullable with a value boxes to the plain underlying value.

Next: Enums and Flags