-
Notifications
You must be signed in to change notification settings - Fork 2
CSharp Nullability Basics
Joe Care edited this page Dec 22, 2025
·
1 revision
This lesson introduces nullable value and reference types, and how to handle null safely.
Related wiki pages:
- Exceptions and robustness:
CSharp-Exceptions-TryCatch.md - Properties and initialization:
Lessons.md(to be renamed to a properties-focused file)
Official docs:
- Nullable reference types: https://learn.microsoft.com/dotnet/csharp/nullable-references
int? maybeValue = null; // nullable int
if (maybeValue.HasValue)
{
Console.WriteLine(maybeValue.Value);
}
else
{
Console.WriteLine("No value");
}int? is shorthand for Nullable<int>.
public static void PrintIfNotNull(string? input)
{
if (input != null)
{
Console.WriteLine($"Input: {input}");
}
else
{
Console.WriteLine("Input is null.");
}
}string? text = null;
int? length = text?.Length; // null if text is null
int lengthOrZero = text?.Length ?? 0; // 0 if text is null
string result = text ?? "default"; // "default" if text is null-
?.stops evaluation if the left side isnull. -
??provides a fallback value if the left side isnull.
- Avoid dereferencing possibly-null values without checks.
- Enable nullable annotations in your project (
<Nullable>enable</Nullable>in the project file) for better compiler warnings. - Combine null checks with exception handling where appropriate (
CSharp-Exceptions-TryCatch.md).
- Apply these operators in your own classes and property accessors.
- Explore advanced patterns like
ArgumentNullException.ThrowIfNullin .NET 6+.