V3105. The 'a' variable was used after it was assigned through null-conditional operator. NullReferenceException is possible.
This diagnostic rule warns you that a 'NullReferenceException' may be thrown during program execution. The analyzer issues this warning when the variable field is accessed without checking whether the variable is 'null'. The key point is that the value of the variable is calculated with an expression that uses the null-conditional operator.
Let's look at the 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 that 'person' can be 'null'. In this case, the 'ToString()' function is not executed and 'null' is written to the 'parentName' variable. A 'NullReferenceException' is thrown when trying to read the 'Length' property of the 'ParentName' variable.
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', we return the string length. Otherwise, we return 0.
An error can occur if a value obtained using null-conditional is passed to a method, constructor, or assigned to a property without checking.
Let's look at the example:
void UsersProcessing(Users users)
{
IEnumerable<User> usersList = users?.GetUsersCollection();
LogUserNames(usersList);
}
void LogUserNames(IEnumerable<User> usersList)
{
foreach (var user in usersList)
{
....
}
}
The 'usersList' variable is passed as an argument to the 'LogUserNames' method. The variable can be "null" since the null-conditional operator is used to get the value. The passed collection is traversed within 'LogUserNames'. To do this, 'foreach' is used, and the collection will have the 'GetEnumerator' method called. If 'userList' is set to 'null', an exception of the 'NullReferenceException' type is thrown.
Fixed code may look as follows:
void UsersProcessing(Users users)
{
IEnumerable<User> usersList = users?.GetUsersCollection();
LogUserNames(usersList ?? Enumerable.Empty<User>());
}
void LogUserNames(IEnumerable<User> usersList)
{
foreach (var user in usersList)
{
....
}
}
The result of executing 'users?.GetUsersCollection()' is assigned to the 'usersList' variable. If the variable returns 'null', an empty collection will be passed to the 'LogUserNames' method. This will help avoid 'NullReferenceException' when traversing 'usersList' in 'foreach'.
This diagnostic is classified as:
You can look at examples of errors detected by the V3105 diagnostic. |