Nullable Reference TypesIntermediate
1Question 1 of 1
csharpHow do Nullable Reference Types prevent NullReferenceExceptions in modern C#?
Explanation & Concept
Introduced in C# 8, Nullable Reference Types (`#nullable enable`) differentiate between non-nullable reference types (`string`) and nullable reference types (`string?`).
The compiler produces warnings whenever a nullable variable is dereferenced without prior null checks or the null-forgiving operator (`!`).
Code Example
csharp
#nullable enable
public class UserProfile {
public string RequiredUsername { get; set; } // Cannot be null
public string? OptionalBio { get; set; } // Can be null
public UserProfile(string username) {
RequiredUsername = username;
}
public void PrintBioLength() {
// Warning if accessed directly: OptionalBio.Length
// Safe access:
int length = OptionalBio?.Length ?? 0;
Console.WriteLine($"Bio characters: {length}");
}
}How It Works & Key Takeaways
Enabling nullable reference types brings compile-time null safety to C#, preventing unexpected `NullReferenceException` crashes in production.
Mock Test · 1 Questions · Optional
Ready for Garbage Collection & IDisposable?
Take a quick test to evaluate yourself, or move straight to the next module.
Intermediate3 questions