Nullable reference types make reference types non-nullable by default, but the guarantee is compile-time only: string? and string are the same System.String at runtime. Khalid Abuhakmeh separates what the compiler checks from what the CLR silently ignores.
Key points
- string? is System.String at runtime; typeof(string?) fails with CS8639 because no separate nullable type exists.
- Declared annotations are stored as [Nullable] and [NullableContext] metadata attributes, which the CLR never enforces.
- <Nullable>enable</Nullable> in Directory.Build.props covers the whole solution; #nullable restore returns a file to the project default.
- For CS8618, prefer required, a primary constructor parameter or a sensible default over null!.
- A missing JSON property leaves a non-nullable member null; required catches it, RespectNullableAnnotations alone does not.
- [NotNullWhen(true)] and [MemberNotNull] carry nullability facts across method boundaries where flow analysis cannot see.
Why it matters
Anyone joining a codebase that already has <Nullable>enable</Nullable> inherits a wall of warnings and, too often, a null! sprinkled wherever CS8618 appeared. The article's value is the boundary it draws: nullable annotations protect you from your own code and from annotated packages, nothing more, so data arriving through JSON, reflection or unannotated libraries still needs real validation at the edge.
On a legacy solution, put the setting in Directory.Build.props and migrate file by file with #nullable enable; otherwise the warning count buries the two or three that point at genuine bugs. Making required the default for new models is the cheaper habit to build early. Maybe
Real-world use
- DTO, entity and options classes whose non-nullable properties are set outside the constructor
- EF Core entities whose properties the framework populates by reflection
- API and integration code that deserializes JSON arriving from outside the build
- Try* helpers such as a TryGetConfig extension over IConfiguration
This summary was generated by the agent from the original post on Khalid Abuhakmeh. The full text and all rights belong to its author and publisher. Go to original