Reputation: 46415
We recently had an issue where we called a dictionary to retrieve a value, expecting the key to be present. It wasn't leading to a process breaking.
Does ReSharper have the functionality to check for this like I've heard it can for null objects?
Here is an example to support what I am talking about:
Dictionary<String, Entity> allEntities =
new Dictionary<String, Entity>(SringComparer.OrdinalIgnoreCase);
allEntities.AddMany(db.GetAllEntities());
Entity thisEntity = allEntities[entityID];
// <-- error here as EntityID isn't in all entities...
I would like ReSharper to be able to say I haven't checked the dictionary like so:
if (allEntities.ContainsKey(entityID))
...
As an FYI, I don't have ReSharper, but this would be one more thing to add in to the business case to get it for all developers.
Upvotes: 0
Views: 306
Reputation: 6578
Even if it could (which I don't think it does), all it would do is warn you that the key might not be in the dictionary - just like it warns you that an object might be null. The onus is still on you to add in the code to check if you think it is necessary.
I think that such a feature would be a burden more than a blessing if it warned you about every dictionary access you made. Then you could argue that you wanted it to warn you about every other type of collection access or any and every exception that could possibly be thrown. The take home message here is that you should rely more on unit testing to catch such issues rather than static analysis tools
EDIT:
Since ReSharper doesn't have this functionality, if you really want it, you could think about writing it yourself with the new Roslyn APIs. See this article for an example of how to write a code analyzer
Upvotes: 8
Reputation: 12064
I have currently installed ReSharper 6, and at least with my settings, it does not warn me to check a Dictionary
with ContainsKey
before accessing its value.
Upvotes: 2
Reputation: 8776
Resharper is a tool used at compile time. How could it possibly know what values are going to be put in a dictionary at runtime?
You can check the dictionary to see if it has the value you want before doing anything with it.
Entity thisEntity;
if (allEntities.TryGetValue(entityID, out thisEntity)){
//DoStuff with thisEntity
}
or just use if (allEntities.ContainsKey(entityID)){}
Upvotes: 2