Collection access analysis
Besides analyzing values of collection items, ReSharper also analyzes each collection you use as a whole — it warns you when a collection is never filled or modified even if there is a read access to this collection:
![ReSharper warns you that a collection is read before ever being filled or modified. ReSharper warns you that a collection is read before ever being filled or modified.](https://resources.jetbrains.com.cn/help/img/dotnet/2024.2/LibCollectionNeverUpdated.png)
or instead, if a collection is never read:
![ReSharper warns you that a collection is never read. ReSharper warns you that a collection is never read.](https://resources.jetbrains.com.cn/help/img/dotnet/2024.2/CollectionIsNeverUsed.png)
All standard collection types are analyzed this way by default. If necessary, you can also apply this analysis to your custom collections that derive from IEnumerable
. In this case, you need to tell ReSharper how invocations of collection’s public methods will affect the contents of the collection. To do so, mark the methods of your collection class with the [CollectionAccessAttribute], which should have one of four flags: None
, Read
, ModifyExisitingContent
, UpdatedContent
(the difference between the last two flags is that UpdatedContent
means that the marked function can also add new elements to the collection). Here is a simple example to illustrate this:
![Using JetBrains.Annotations to improve code analysis of collection access Using JetBrains.Annotations to improve code analysis of collection access](https://resources.jetbrains.com.cn/help/img/dotnet/2024.2/CollectionAccess.png)