astralmaster
astralmaster

Reputation: 2465

Possible NullReferenceException ReSharper code analysis C#

ReSharper code analysis tells me that in following code snippet

if (users.Select(a => a.id).Contains(user_id))
{
    return users.FirstOrDefault(a => a.id == user_id).type == 2;
}

the line return users.FirstOrDefault(a => a.id == user_id).type might result in a possible System.NullReferenceException. Is this true given that I already check whether this specific user_id exists in the users container?

class users
{
   int id {get; set;}
   int other_stuff {get; set;}
}

Upvotes: 0

Views: 456

Answers (2)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

If you are sure that you have such element in your collection then you can just use .First:

if (users.Select(a => a.id).Contains(user_id))
{
     return users.First(a => a.id == user_id).type == 2;
}

However, it is better to use .FirstOrDefault and null check instead of Contains so that you don't lookup your collection twice:

var foundItem = users.FirstOrDefault(x => x.id == user_id);
if (foundItem != null)
{
    return foundItem.type == 2;
}

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Is this true given that I already check whether this specific user_id exists in the users container?

Yes, this is warning is correct, because users may be changed concurrently between the call to Contains and the call to FirstOrDefault. ReSharper's logic analyzer does not assume exclusive access to the container, so issuing a warning is the right behavior.

You can fix this warning with a null-conditional operator:

var optType = users.FirstOrDefault(a => a.id == user_id)?.type;

if (optType.HasValue) {
    return optType == 2;
}

Upvotes: 1

Related Questions