Nullability
Enable nullable awareness
Modern projects enable nullable reference types so the compiler warns about possible nulls.
string title = "C#";
string? maybeMissing = null;
Console.WriteLine(title);
Check before use
Test for null or use the null-conditional operator.
int? length = maybeMissing?.Length;
Console.WriteLine(length ?? 0);
Null-forgiving operator
The ! operator tells the compiler you are sure. Prefer real checks when possible.
// only when you truly know it is not null
// Console.WriteLine(maybeMissing!.Length);
Null habits
- Annotate intentional nulls with
? - Return empty collections instead of null when practical
- Use
ArgumentNullException.ThrowIfNullat API boundaries - Treat warnings as errors in serious projects
Comments
One comment per signed-in account. Comments are saved with this page’s URL.