Problem
When enabling nullable reference types in a .NET project (using either <Nullable>enable</Nullable> or #nullable enable), the JetBrains ContractAnnotation attributes, which enhance nullability checks and analysis, seem not to work as expected. This includes checks that go beyond what the .NET nullable type annotations provide.
Cause
In the context where nullable reference types (NRT) are enabled, the reference types (string and string?) explicitly communicate nullability to the compiler. The JetBrains annotations like [NotNull], [CanBeNull], and [ContractAnnotation], which are intended to function in a non-nullable reference type context (#nullable disable), are overridden by the compiler's syntax and analysis rules for nullability.
Resolution
To express nullability contracts in an NRT-enabled context, utilize the nullable reference type features alongside Microsoft-provided attributes, which are understood by the compiler. For instance, converting the following signature:
[ContractAnnotation("null => null; notnull => notnull")]
string Trim(string? path)
can be done in the following way:
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(nameof(path))]
string? Trim(string? path)
This way, the compiler correctly interprets the nullability logic. For further insights into nullable reference type annotations and their usage, refer to Microsoft's documentation: Nullable reference types.
Comments
0 comments
Please sign in to leave a comment.