Nullable Reference Types in C#: Why You Should Care
Make your C# code safer and clearer by mastering nullable reference types — here’s why it matters.
🧠 Why Nullable Reference Types Exist
C# has always had a tricky blind spot: reference types can be null by default, and it’s up to the developer to avoid null reference exceptions.
You’ve probably run into this:
string name = GetUserName(); // Could be null 😬
Console.WriteLine(name.Length); // Boom 💥 NullReferenceExceptionThis is where nullable reference types (NRTs) help. Introduced in C# 8.0, they let the compiler warn you when you might be assigning or accessing a null reference, before you even run the code.
✅ How to Enable It
Add this to your .csproj file:
<Nullable>enable</Nullable>🧪 How It Works
Once enabled, C# will treat all reference types as non-nullable by default.
string name = null; // ❌ Warning: possible null assignment
string? nickname = null; // ✅ This is okayNow the compiler helps you track:
Where you might return or assign null
Where you forgot to check for null
Where you’re not using null-safety
👨💻 A Simple Example
// Wrong
public class User {
public string Name { get; set; } // ❌ Warning: not initialized
public string? Email { get; set; } // ✅ Nullable allowed
}
// Fix
public class User {
public string Name { get; set; } = string.Empty;
public string? Email { get; set; }
}This makes your intent explicit, which helps other developers — and future you — understand what’s allowed.
🔍 When You Should Use It
Use nullable reference types if you:
Want to avoid runtime null exceptions
Are working on a team project or open-source
Are maintaining a growing codebase
⚠️ Gotchas to Watch Out For
You’ll still need to be thoughtful — NRTs are not a silver bullet.
Legacy code may require a migration strategy.
You might get lots of warnings at first — that’s okay! Fix them bit by bit.
🚀 Pro Tips
Use ! (null-forgiving operator) sparingly. It’s a shortcut, not a fix:
string name = GetName()!;Use ?? and ??= to handle fallbacks:
string? title = null;
string display = title ?? "Untitled";💬 Final Thoughts
Nullable reference types help you write more predictable, self-documented code. It’s a small change that adds big safety, especially as your app grows.
If you’re just starting out with them, take it slow, but don’t ignore them.
🙌 Stay in the loop:
☕️ Enjoying the content? Buy me a coffee to support more writing like this.
Thanks for reading!
See you,
The Boy Tech


