With Nullable Reference Types enabled, the compiler treats all reference types as non-nullable by default. Types that can be null must be explicitly marked with ? (e.g. string?).
C# Nullable Reference Types
Prevent null reference exceptions with compiler-enforced null safety.
Key Takeaways: C# Nullable Reference Types
Mastering C# Nullable Reference Types helps you write clean and reliable C# code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
C# Nullable Reference Types Code Example
C#using System;
class Program {
static void PrintLength(string? input) {
if (input != null) {
Console.WriteLine($"Length: {input.Length}");
} else {
Console.WriteLine("Input was null");
}
}
static void Main() {
PrintLength("Hello C#");
PrintLength(null);
}
}
Output
Length: 8 Input was null
Run this example on your own computer. The "Get Started" lesson shows how to set it up.
Finished this lesson?
Mark it complete to track your progress.
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services