Code inspection: Conditional access qualifier expression is not null according to nullable reference types' annotations
Category: Redundancies in Code
ID: ConditionalAccessQualifierIsNonNullableAccordingToAPIContract
EditorConfig: resharper_conditional_access_qualifier_is_non_nullable_according_to_api_contract_highlighting=[error|warning|suggestion|hint|none]
Language: C#
Requires SWA: No
tip
If nullable reference types (NRT) are enabled, this inspection reports redundant conditional access operators (?.
) for expressions that are guaranteed not to be null
due to the nullable context and annotations.
In the example below, GetRnd()
is declared with the return type Rnd
(without the ?
annotation), which means that the return value will never be null in the nullable-aware context. Since rnd
gets this return value, it will be also considered as non-nullable, making conditional access operator ?.
in rnd?.TrueOrFalse
unnecessary. Therefore, ReSharper suggests replacing rnd?.TrueOrFalse
with rnd.TrueOrFalse
.
Suboptimal code
#nullable enableclass Test { Test() { var rnd = GetRnd(); if(rnd?.TrueOrFalse is true) Console.WriteLine("True"); } Rnd GetRnd() => new Rnd();}public class Rnd{ public bool TrueOrFalse => new Random().Next(2) == 0;}
After the quick-fix
#nullable enableclass Test { Test() { var rnd = GetRnd(); if(rnd.TrueOrFalse is true) Console.WriteLine("True"); } Rnd GetRnd() => new Rnd();}public class Rnd{ public bool TrueOrFalse => new Random().Next(2) == 0;}
NRT improve overall precision of the nullability analysis, but there are cases when NRT contracts can be violated, for example, when values are coming from code without #nullable
context. In such cases, you may get false positive warnings for nullability checks . You can choose to ignore nullable API contracts and report a problem only when previous operations with the value in your code guarantee that it can or cannot be null.
You can change this behavior right from the AltEnter menu:
![ReSharper: Nullable reference types ReSharper: Nullable reference types](https://resources.jetbrains.com/help/img/dotnet/2024.3/nrt_false_positive.png)
... or using the Nullable reference types' warnings mode option on the Code Inspection | Settings page of ReSharper options .
When ReSharper ignores nullable API contracts, nullability analysis relies on the program control flow to report redundant null checks. It will use another inspection for that. For example:
var myString = ApiMethod();
if (myString is null)
throw new ApplicationException("the string is null");
// warning 'Expression is always true'
// 'myString' cannot be null because it's already checked for null in our code
if (myString != null)
Console.WriteLine(myString);
For more information about NRT and how ReSharper supports them, watch this webinar recording: