V3153. Dereferencing the result of null-conditional access operator can lead to NullReferenceException.
The analyzer found a potential error that may cause the null reference's dereferencing. The code contains the '?.' operator's result that is dereferenced immediately - explicitly or implicitly.
A 'NullReferenceException' exception may be thrown, for example, in cases below:
- You used the null-conditional operator on a potentially null element, placed the expression in parentheses, and dereferenced the result.
- The 'foreach' statement contains the null-conditional operator.
The scenarios above may lead to one of the following:
- The program throws a 'NullReferenceException' exception if you conditionally access a 'null' reference.
- The program always works correctly, because the reference you use for conditional access is never 'null'. In the second case, checking for 'null' is unnecessary.
Let's take a closer look at the first case. This code may throw an exception:
var t = (obj?.ToString()).GetHashCode();
In the 'obj?.ToString()' expression, if the 'obj' object is 'null', the 'ToString()' method is not called. This is how the conditional access operator works. However, since the 'GetHashCode' method is outside the null-conditional expression, it is called no matter the expression's result.
Below is the fixed code:
var t = obj?.ToString().GetHashCode();
The expression above does not have the dangerous dereferencing. Additionally, the 't' variable now has the 'Nullable<int>' type, which correctly reflects its contents as potentially containing the 'null' value.
Let's take a look at a different example. Here, checking for 'null' is excessive because of the safe dereferencing:
object obj = GetNotNullString();
....
var t = ((obj as String)?.Length).GetHashCode();
This code always works correctly. The 'obj' object is always of the 'String' type, therefore checking type after casting is unnecessary.
Below is the fixed code:
var t = ((String)obj).Length.GetHashCode();
The example below shows a foreach statement that contains the null-conditional operator:
void DoSomething(string[] args)
{
foreach (var str in args?.Where(arg => arg != null))
....
}
If the 'args' parameter is 'null', the 'args?.Where(....)' expression also evaluates to 'null' because of the '?.' operator. When the 'foreach' loop to iterates through the collection, a 'NullReferenceException' exception is thrown. This happens because the 'GetEnumerator()' method is implicitly called for the 'args?.Where(....)', and this dereferences the null reference.
You can fix the code in the following way:
void DoSomething(string[] args)
{
foreach (var str in args?.Where(arg => arg != null)
?? Enumerable.Empty<string>())
....
}
This diagnostic is classified as:
You can look at examples of errors detected by the V3153 diagnostic. |