Search code examples
c#c#-4.0sonarqubenullablesonarlint

Sonar Cube throws bug saying as "is null on at least one execution path."


c# code

if (numlist.Any())
{
    numlist.FirstOrDefault(c => c.Number == request.Number).ValCount = request.Count;
}

Sonar Cube throws bug message saying as 'numlist.FirstOrDefault(c => c.Number == request.Number)' is null on at least one execution path.

I have tried to put nullable ? like this -> numlist? but it doesn't works.

Can you please assist how to resolve this issue


Solution

  • The code says:

    // if there are any entries in numlist
    if (numlist.Any())
    {
        // find the first entry whose Number matches the request,
        // or if not found, return the default for the numlist's
        // type, which is null according to the warning
        numlist.FirstOrDefault(c => c.Number == request.Number)
            // set the ValCount property of the result to request.Count
            .ValCount = request.Count;
    }
    

    The problem is that FirstOrDefault(predicate) returns a default value if none of the elements in the source collection matched the predicate.

    In other words: it's not guaranteed that there's any entry in numlist that has Number == request.Number, in which case FirstOrDefault() will return null.

    You can't assign ValCount on null, that will throw a NullReferenceException.

    Furthermore, combining Any() and FirstOrDefault() is superfluous in this case. You can refactor the code like this:

    var requestedItem = numlist.FirstOrDefault(c => c.Number == request.Number);
    
    if (requestedItem == null)
    {
        throw new ArgumentException($"Cannot find item with number '{request.Number}'");
    }
    
    requestedItem.ValCount = request.Count;
    

    Guarding execution (and at the same time pleasing the static analysis), guaranteeing that a situation which you think might never happen, will never happen.