skip to content

Nullable Value Types

int? is Nullable<int>, with HasValue, Value, lifted operators and boxing to null. Interviewers ask what a null comparison returns and how int? differs from string?.

on this pageshow

explore

questions

5

In C#, what is `int?`, and what do `HasValue`, `Value` and `GetValueOrDefault()` do when it holds no value?

level: juniorimportance: must knowfreq 72%

answer

  1. a struct, not a reference
  2. a flag beside the payload
  3. one member checks, one does not
  4. default of T versus your fallback

basics

~10 s

int? is shorthand for the struct Nullable<int>. When it is empty, HasValue is false, Value throws InvalidOperationException, and GetValueOrDefault() returns 0, or the fallback you pass to GetValueOrDefault(T).

solid answer

~40 s

`int?` is the C# spelling of `Nullable<int>`, a struct that holds a `bool` flag next to an `int` field, so it adds an empty state to a value type without a heap allocation. `HasValue` reports the flag. `Value` returns the `int` when the flag is set and throws `InvalidOperationException` ("Nullable object must have a value.") when it is not; the explicit cast `(int)age` fails the same way. `GetValueOrDefault()` never throws: an empty instance returns `default(int)`, which is 0, and `GetValueOrDefault(-1)` returns the fallback you pass. In new code `if (age is int a)` tests and unwraps in one step, and `age ?? -1` gives a fallback inline. With nullable warnings enabled, reading `.Value` on an instance that may be empty raises warning CS8629.

code

csharp · 27 lines
csharp
using System;

var response = new SurveyResponse { Age = null, LastLogin = new DateTime(2026, 9, 30) };

Console.WriteLine(response.Age.HasValue);              // False
Console.WriteLine(response.Age.GetValueOrDefault());   // 0
Console.WriteLine(response.Age.GetValueOrDefault(-1)); // -1
Console.WriteLine(response.Age ?? -1);                 // -1

if (response.LastLogin is DateTime seen)
    Console.WriteLine($"Last login {seen:yyyy-MM-dd}");

try
{
    int age = response.Age.Value;                      // CS8629 warning; throws here
    Console.WriteLine(age);
}
catch (InvalidOperationException ex)
{
    Console.WriteLine(ex.Message);                     // Nullable object must have a value.
}

class SurveyResponse
{
    public int? Age { get; set; }
    public DateTime? LastLogin { get; set; }
}

go deeper

for a junior

Recall that int? is Nullable<int>, that Value throws on an empty instance and GetValueOrDefault does not, and that is int a unwraps safely.

for a middle

Explain the flag-plus-field layout, why the default of int? is empty, why GetValueOrDefault returns the default of T, and when CS8629 appears.

for a senior

Show judgment about where a missing value becomes a substitute: an optional field silently turned into 0 corrupts statistics long before anything throws.

for a principal

Frame the team rule: keep optional numeric data as T? to the edge, forbid bare .Value reads behind nullable warnings, and make every fallback explicit in review.

## What `int?` is `int?` is a spelling, not a type of its own. For any **non-nullable value type** `T`, the compiler translates `T?` into the generic struct `System.Nullable<T>`, and `typeof(int?)` prints ``System.Nullable`1[System.Int32]``. The struct, as the .NET source declares it, has two fields: - a read-only `bool` flag, `hasValue`, that says whether a payload is present - a `T` field, `value`, that holds the payload Because `Nullable<T>` is a **struct**, an `int?` lives wherever an `int` would: in a local, a field or an array element. Creating one never allocates. The cost is size: on .NET 10, `Unsafe.SizeOf<int?>()` reports 8 bytes, twice an `int`, because the flag is padded to the payload's alignment. The struct is declared `where T : struct`, and the compiler reads that constraint as "non-nullable value type", so `Nullable<int?>` is rejected with **CS0453**. `string?` is something else entirely: an annotation on a reference type that the nullable reference types feature checks at compile time, with no wrapper struct behind it. The **default value** of an `int?` (the `default` literal, `new int?()`, an unassigned field) is the empty instance: `HasValue` is `false`. ## `int?` versus `string?` Interviewers often ask the two together, because the same `?` means different things on each side of the type system: | | `int?` | `string?` | |---|---|---| | Run-time type | `Nullable<int>`, a struct | `string`, the same type as `string` | | How "no value" is stored | the flag is `false` | a null reference | | Members you can call | `HasValue`, `Value`, `GetValueOrDefault` | only `string`'s own members | | What enforces it | the type itself, at run time | compiler warnings, only with nullable enabled | | Default of the plain type | `int` is 0, never null | `string` can still be null at run time | The practical consequence: `int` can never be null, so the `?` on `int?` adds a capability, whereas `string` could always be null, so the `?` on `string?` only documents intent for the compiler's flow analysis. ## Reading the value | Member | Holds 42 | Empty | |---|---|---| | `HasValue` | `true` | `false` | | `Value` | 42 | throws `InvalidOperationException` | | `GetValueOrDefault()` | 42 | 0, the default of `int` | | `GetValueOrDefault(-1)` | 42 | -1 | | explicit cast `(int)age` | 42 | throws `InvalidOperationException` | - `Value` checks the flag first; the exception message is "Nullable object must have a value." - `GetValueOrDefault()` returns the stored field without checking. An empty instance's field is zero-initialised, so the result is `default(T)`: 0 for `int`, `false` for `bool`, `DateTime.MinValue` for `DateTime`. - The explicit conversion `(int)age` reads `Value` (the runtime source declares the operator as `value!.Value`), so it throws the same exception. ## Reading it safely 1. **Type pattern**: `if (response.Age is int age)` matches only a non-empty instance and binds a plain `int`. The C# documentation recommends it for new code because the unwrapped variable exists only where it is safe. 2. **`HasValue` then `Value`**: the older idiom, equivalent but easier to get wrong when the check and the read drift apart. 3. **Fallback**: `response.Age ?? -1` or `response.Age.GetValueOrDefault(-1)`; both return the stored value when one is present and the fallback otherwise. 4. **Compare with `null`**: `response.Age != null` compiles to a `HasValue` test. The pattern must name the underlying type. `if (age is int? a)` is rejected with **CS8116**: "It is not legal to use nullable type 'int?' in a pattern; use the underlying type 'int' instead." ## What the compiler warns about With nullable warnings enabled (the `Nullable` project property set to `enable` or `warnings`; recent .NET project templates set `enable`, and file-based apps run with it on), flow analysis tracks `Nullable<T>` as well as reference types. Reading `.Value`, or casting to `int`, when the instance may be empty raises **CS8629**, "Nullable value type may be null." After `if (age.HasValue)` or `if (age != null)` the warning goes away. With the property set to `disable` there is no warning, and the exception at run time is the first signal. ## In a survey model Take a `SurveyResponse` with `int? Age` and `DateTime? LastLogin`. An empty `Age` means the respondent skipped the question, which 0 cannot say. That is the trap in `GetValueOrDefault()`: it turns "skipped" into a real-looking age of zero, which then drags an average or a minimum down. Keep the empty state until the point where a substitute means something, and when you substitute, write the fallback out with `??` or `GetValueOrDefault(T)` so the reviewer sees it. A short checklist for such a model: - Declare a field `int?` only when "not given" is a real state; a required field stays `int`. - Read it with a pattern or `HasValue` before arithmetic that must not see a missing value. - Choose fallbacks per use: a display can show "not given", while an average should skip the response.

  • Why can `GetValueOrDefault()` be the wrong choice for an optional survey age?
    It returns `default(int)`, 0, for a skipped answer, so a missing age becomes a believable age of zero and pulls averages and minimums down. Keep the empty state until a substitute is meaningful, or pass an explicit sentinel with `GetValueOrDefault(-1)` or `??` so the substitution is visible in the code.
  • Can you test and unwrap an `int?` with `if (age is int? a)`?
    No. A declaration pattern cannot name a nullable value type; the compiler reports CS8116 and tells you to use the underlying type. `if (age is int a)` matches only a non-empty instance and binds a plain `int`, so the null test and the unwrapping happen together.
  • Does `Value` cost more than `GetValueOrDefault()`?
    Slightly: `Value` tests the flag and calls a throw helper when it is false, while `GetValueOrDefault()` returns the stored field with no test. The field of an empty instance is zero-initialised, which is why the no-argument overload returns the default of `T` rather than garbage.

A paper form field with a separate 'not answered' tick box. The tick is HasValue; Value insists on checking the tick before you read the box, while GetValueOrDefault() reads the box as it is, blank meaning zero.

  • int? is a reference type, which is why it can hold null
  • Value returns 0 when the int? is empty
  • GetValueOrDefault() throws when there is no value
  • Casting an empty int? to int gives 0
  • int? and string? are the same kind of nullable
  • Every int? allocates a small object on the heap
open as a page

In C#, what do lifted operators return when an `int?` operand is null, and how do `==` and `!=` treat two nulls?

level: middleimportance: must knowfreq 58%

basics

~20 s

Lifted arithmetic and bitwise operators on int? return null when either operand is null, so age + 5 is null and never throws. Equality returns a plain bool: null == null is true and null != 5 is true.

open as a page

In C#, what does boxing an `int?` produce when it is empty and when it holds 42, and why does `GetType()` never report `Nullable<int>`?

level: seniorimportance: should knowfreq 38%

basics

~10 s

Boxing an empty int? produces a null reference; boxing one that holds 42 boxes the plain int. No boxed Nullable<int> ever exists, so GetType() reports System.Int32, or throws NullReferenceException on an empty instance.

open as a page

In a C# generic method returning `T?`, why is `T?` a `Nullable<T>` under `where T : struct` but plain `int` when an unconstrained `T` is `int`?

level: seniorimportance: should knowfreq 28%

basics

~20 s

Under where T : struct, T? is Nullable<T>, so the method can return null and callers get an empty value. On an unconstrained T, T? is only an annotation: for T = int it is plain int, and return default yields 0.

open as a page

A C# survey report counts responses with `Age >= 18` and with `Age < 18` on an `int? Age`; why don't the two counts add up to the total?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Lifted ordering comparisons on int? return false whenever an operand is null, so a response with no age is neither >= 18 nor < 18 and drops out of both counts; !(Age < 18) adds them back.

open as a page