C#
Nullable Reference Types
6 question(s)
What are nullable reference types (NRTs)?
Beginner
An opt-in compiler feature where reference types are non-null by default and nullability is expressed with ?, giving warnings when you might dereference null.
string name = "x"; // must not be null
string? middle = null; // may be null
Real-world example
Catching potential NullReferenceExceptions at compile time instead of in production.
What is the null-forgiving operator (!) and when is it appropriate?
Beginner
! tells the compiler you know a value isn't null, suppressing the warning. Use it sparingly when you have knowledge the compiler lacks — overuse hides real bugs.
var name = dict[key]!; // you guarantee the key exists
Real-world example
Asserting non-null after a framework guarantees initialization the compiler can't see.
What is the difference between ?., ?? and ??=?
Intermediate
?. is null-conditional access (returns null instead of throwing); ?? is null-coalescing (fallback value); ??= assigns only if the target is null.
int len = name?.Length ?? 0;
cache ??= new();
Real-world example
Safely reading a nested property and defaulting when any link is null.
How do nullable annotations affect API design?
Intermediate
Method signatures document intent: a string? parameter accepts null, a string return promises non-null. This forms a contract callers can rely on.
public User? FindById(int id); // may return null
public string GetName(User u); // never null
Real-world example
A repository returning User? signals to callers they must handle 'not found'.
What are nullable attributes like NotNullWhen and MaybeNull for?
Advanced
They express nullability that depends on outcomes the type alone can't show, improving flow analysis for helpers like TryGet.
bool TryGet(string key, [NotNullWhen(true)] out User? user);
Real-world example
After TryGet returns true, the compiler knows user is non-null, so no warning on use.
How do you adopt NRTs safely in a large existing codebase?
Advanced
Enable it gradually (per-file #nullable enable or project-wide with warnings-as-messages first), fix real warnings, and avoid blanket ! suppressions that mask bugs.
#nullable enable // start file-by-file
Real-world example
A team turns NRTs on module by module so the warning load stays manageable.