C# 8+ nullable reference types (NRT) add compile-time warnings for possibly-null strings and objects—closing a gap where reference types could always be null at runtime like in Java. Value types already had int? syntax.
Annotations
#nullable enable
string name = GetName(); // warning if GetName may return null
string? maybe = GetName(); // explicitly nullable
if (maybe is not null) {
Console.WriteLine(maybe.Length);
}
The compiler tracks flow state after null checks—pattern matching integrates cleanly.
Null-forgiving operator
string sure = GetName()!; // suppress warning—use sparingly
Prefer guard clauses and validation over sprinkling !.
Important interview questions and answers
- Q: string vs string?
A:string?tells the compiler null is allowed; plainstringis non-null by contract when NRT is enabled. - Q: Do NRTs prevent NullReferenceException?
A: No—they are warnings/analysis aids; runtime nulls still throw unless you check.
Self-check
- What suffix marks a nullable reference type?
- When is the ! operator appropriate?
Tip: Enable #nullable enable in new files—string? documents possible null; plain string is non-null by contract.
Interview prep
- string vs string?
string?tells the compiler null is allowed; plainstringis non-null by contract when NRT is enabled.- Do NRTs prevent NullReferenceException?
No—they are compile-time warnings; runtime nulls still throw unless you check.