skip to content

In C#, what does T? mean on a method of an unconstrained generic Store<T>, and which nullable attributes express the same contract?

level: seniorimportance: should knowfreq 30%

answer

  1. no struct or class constraint
  2. an annotation, not a new type
  3. value types stay as they are
  4. [MaybeNull] on a return
  5. the default constraint on overrides

basics

~20 s

On an unconstrained T, T? is an annotation meaning 'may be default': for T = string it is string?, for T = int it stays int, not int?. So Store<int>.GetOrDefault returns 0 for a missing key.

solid answer

~40 s

Since C# 9, `T?` is allowed on a type parameter with no `class` or `struct` constraint, and it is a nullable **annotation**, not `Nullable<T>`. With `T = string` the return is `string?`, so dereferencing it gets CS8602; with `T = int` the type is plain `int`, so a missing key comes back as `default(int)`, which is `0`, and `int count = store.GetOrDefault(k);` compiles. Reflection reports the return type as `System.Int32`. On a return value `T?` means the same as `[return: MaybeNull] T`, and on a parameter the same as `[AllowNull] T`; in C# 8 those attributes were the only way, since `T?` there was error CS8627. An override needs `where T : default` to read `T?` this way. If callers must tell a missing key from a stored 0, use a Try method instead.

code

csharp · 18 lines
csharp
var hits = new Store<int>();
var owners = new Store<string>();

int count = hits.GetOrDefault("missing");          // T? with T = int is plain int
string? owner = owners.GetOrDefault("missing");   // T? with T = string is string?

Console.WriteLine(count);
Console.WriteLine(owner is null);
Console.WriteLine(typeof(Store<int>).GetMethod("GetOrDefault")!.ReturnType);

class Store<T>
{
    private readonly Dictionary<string, T> _items = new();

    public void Set(string key, T value) => _items[key] = value;

    public T? GetOrDefault(string key) => _items.TryGetValue(key, out var v) ? v : default;
}

go deeper

for a junior

Recall that int? is Nullable<int>, but that T? on an unconstrained generic is only an annotation and leaves int as int.

for a middle

Walk through what T? becomes for string, string?, int and int?, and why an annotation cannot change int into int?.

for a senior

Connect T? to [MaybeNull] and [AllowNull], explain the default constraint on overrides, and spot the 0-versus-missing bug in generic caches.

for a principal

Decide how generic APIs signal absence: a Try method, a struct-constrained overload, or an annotated T?, and keep that choice consistent across the codebase.

## Three meanings of the question mark In C# the `?` suffix on a type means different things depending on what the type is: | Declaration | Meaning of `T?` | `T = int` | `T = string` | |---|---|---|---| | `where T : struct` | `Nullable<T>`, a different type | `int?` | not allowed | | `where T : class` | nullable reference annotation | not allowed | `string?` | | no constraint | **"T, or default(T)"** annotation | `int` | `string?` | The third row is the one this question is about. Before C# 9 it did not compile: `T?` on an unconstrained type parameter was error **CS8627** ("A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used."). C# 9 allowed it, with annotation semantics. ## What the caller gets for each type argument Take an in-memory store: ```csharp class Store<T> { private readonly Dictionary<string, T> _items = new(); public T? GetOrDefault(string key) => _items.TryGetValue(key, out var v) ? v : default; } ``` - `Store<string>`: `GetOrDefault` returns `string?`. A missing key gives `null`, and `who.Length` gets **CS8602**. - `Store<string?>`: still `string?`; the annotation never stacks into a "doubly nullable" type. - `Store<int>`: returns `int`. A missing key gives `default(int)`, which is `0`. `int count = store.GetOrDefault("x");` compiles, and `typeof(Store<int>).GetMethod("GetOrDefault")!.ReturnType` is `System.Int32`. - `Store<int?>`: returns `int?`, because `T` itself is already nullable; a miss gives `null`. The important point for code review: **`T?` here never turns `int` into `int?`.** The IL declares the return type as plain `T`, and a nullable annotation cannot change what `T` is when the code runs. ## The attributes it is shorthand for In C# 8, generic APIs expressed the same contract with attributes from `System.Diagnostics.CodeAnalysis`, and the C# 9 proposal defines `T?` as equivalent to them: 1. On a **return value**, `T?` equals `[return: MaybeNull] T`: the result may be null even when `T` is a non-nullable reference type. 2. On a **parameter**, `T?` equals `[AllowNull] T`: callers may pass null even when `T` is non-nullable. The attributes still matter. They appear on older APIs, and `T?` was designed to match them, so a C# 9 or later override of a C# 8 member declared `[return: MaybeNull] T` can write `T?` together with `where T : default`. They also cover cases `T?` cannot express, such as a property whose getter never returns null but whose setter accepts null (`[AllowNull]` on a `T` property). ## Overrides and the default constraint Overrides and explicit interface implementations cannot normally restate constraints, and for compatibility with C# 8 a bare `T?` in them is read as `Nullable<T>`. Overriding `public virtual T? Find<T>()` with `public override T? Find<T>()` therefore fails with **CS0508** and **CS0453**. C# 9 added the **`default` constraint** for this: ```csharp public override T? Find<T>() where T : default => default; ``` `where T : default` is valid only on overrides and explicit interface implementations; anywhere else it is error **CS8823**. ## The design trap: 0 or missing? Because `T?` gives `0` for a `Store<int>` miss, the caller cannot tell "not cached" from "cached zero". Two honest fixes: - Return a `bool` and an out value, `bool TryGet(string key, [MaybeNullWhen(false)] out T value)`, so the result carries the answer. - Provide a separate overload for value types with a `struct` constraint returning `Nullable<T>`, which is covered with nullable value types. The same trap hides in LINQ-style helpers: `FirstOrDefault` on an `IEnumerable<int>` returns `0` for an empty sequence, for exactly this reason. When reviewing a generic API that returns `T?`, ask what a caller with a value type argument is supposed to do with the default, and whether that case was ever tested. Constraints themselves are covered with generic constraints; this question is about what the annotation means when there is no constraint at all.

  • Why does an override need where T : default to use T??
    For compatibility with C# 8, a bare `T?` in an override or explicit implementation is read as `Nullable<T>`, which needs a value type, so the override fails with CS0508 and CS0453. `where T : default`, added in C# 9, tells the compiler it is the unconstrained annotation instead. It is error CS8823 on any other method.
  • When is [MaybeNull] or [AllowNull] still needed instead of T??
    When the declared type must stay `T` but one direction differs: a `T` property whose getter never returns null but whose setter accepts null takes `[AllowNull]`, which `T?` cannot express because it would affect both accessors. They also appear throughout APIs written for C# 8, which `T?` was designed to match.

  • T? on an unconstrained type parameter always means Nullable<T>.
  • GetOrDefault on a Store<int> returns null for a missing key.
  • T? on a generic method still needs a struct or class constraint.
  • [return: MaybeNull] T and a T? return mean different things to callers.
  • where T : default can be added to any generic method.