Open sandboxFocusImprove this doc
  • Article

Checking all non-nullable fields, properties and parameters

If you're already using the nullability feature introduced in C# 8.0, you're aware that C# only reports a warning when there's an attempt to assign a null value to a non-nullable field, property, or parameter. C# does not generate the code that would throw an exception at runtime if this happens. However, if your API is being consumed by code that isn't under your control, it's still a good idea to check all values for null.

If you find this task repetitive, frustrating, and unworthy of clean code, we share your sentiment.

Rejoice, solving this problem is a one-liner with Metalama! Simply call the VerifyNotNullableDeclarations method from your ProjectFabric.

Note

By default, only your public API is verified. To add checks to your internal API, set the includeInternalApis parameter to true.

Example: enforcing all non-nullable fields, properties and parameters

In the following example, we use the VerifyNotNullableDeclarations method to inject null-checks for our complete public API. Yes, in just one line.

1using Metalama.Framework.Fabrics;
2using Metalama.Patterns.Contracts;
3
4namespace Doc.NotNullFabric;
5
6internal class Fabric : ProjectFabric
7{
8    public override void AmendProject( IProjectAmender amender )
9    {
10        amender.VerifyNotNullableDeclarations();
11    }
12}
  • Navigation