IntermediateLesson 8 of 16
Nullable Reference Types – C#
Catch null errors at compile time.
The infamous NullReferenceException can be largely avoided with nullable reference types: string means "never null", string? means "may be null". The compiler warns you when you carelessly use a possible null value. In new projects this is enabled by default via <Nullable>enable</Nullable> in the .csproj.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>Three operators make handling this convenient: ?. (null-conditional access), ?? (fallback value) and ??= (assign only if null).
string? b = null;
Console.WriteLine(b?.Length); // (empty line) – no crash
Console.WriteLine(b?.Length ?? 0); // 0
b ??= "Default";
Console.WriteLine(b); // Default
int? maybe = null; // nullable value type
Console.WriteLine(maybe.HasValue); // False
Console.WriteLine(maybe.GetValueOrDefault(-1)); // -1The compiler tracks the flow: after a null check it knows that the variable is populated. For parameters, you check preconditions with ArgumentNullException.ThrowIfNull.
Console.WriteLine(Laenge(null)); // 0
Console.WriteLine(Laenge("Hello")); // 5
var treffer = Suche(new[] { "Ada", "Bob" }, "C");
Console.WriteLine(treffer ?? "nothing found");
static int Laenge(string? s)
{
if (s is null) return 0;
return s.Length; // here the compiler knows: s is not null
}
static string? Suche(string[] namen, string prefix)
=> namen.FirstOrDefault(n => n.StartsWith(prefix));WarningThe "null-forgiving" operator
! (e.g. wert!.Length) only silences the warning – at runtime it still crashes if the value turns out to be null. Use it sparingly and only when you are sure.