V3105. The 'a' variable was used after it was assigned through null-conditional operator. NullReferenceException is possible.
This diagnostic warns you that a 'NullReferenceException' exception may be thrown during the program's execution. The analyzer issues a warning if you do not check a variable for 'null' and then call the variable's method or access its field or property. The key point is, the variable's value is calculated with an expression that uses the null-conditional operator.
Take a look at this example:
public int Foo (Person person)
{
string parentName = person?.Parent.ToString();
return parentName.Length;
}
In the code above, when initializing the 'parentName' object, we assume 'person' can be 'null'. In this case the 'ToString()' function won't be executed, and 'null' will be written to the 'parentName' variable. When the execution flow accesses the 'parentName.Length' property, a 'NullReferenceException' is thrown.
You can fix the code as follows:
public int Foo (Person person)
{
string parentName = person?.Parent.ToString();
return parentName?.Length ?? 0;
}
Now, if the 'parentName' variable is not 'null', the 'Foo' function returns the string length. Otherwise, it returns 0.
Here's one more example:
void DoSomething(string[] args)
{
var nonNullStrings = args?.Where(arg => arg != null);
foreach (var str in nonNullStrings)
....
}
Similar to the previous example, the 'nonNullStrings' variable initialization assumes the 'args' parameter can be 'null'. In that case, the 'nonNullStrings' variable is also assigned 'null'. When the 'foreach' loop iterates through the collection items, the 'GetEnumerator()' method is implicitly called for 'nonNullStrings'. If 'nonNullStrings' is 'null', a 'NullReferenceException' exception is thrown.
You can correct the code as follows:
void DoSomething(string[] args)
{
var nonNullStrings = args?.Where(arg => arg != null)
?? Enumerable.Empty<string>();
foreach (var str in nonNullStrings)
....
}
This diagnostic is classified as:
You can look at examples of errors detected by the V3105 diagnostic. |