4

I am using FxCop tool for code analysis and it shows an critical errors like "Don't expose generice list" and it suggests that instead of using a list object try to use ICollection.

I tried to replace the List with ICollection but so many places i have insert and Add range methods, i need them anyhow for fulfilling my business logic

"So How I can use Insert,AddRange and other list methods on Icollection without type casting or using ToList() method because if i had to use these methods, then why i should replace the list wiht ICollection"

Please don't mark anything redundantly duplicate if you don't understand what is my issue.

Yogesh
  • 2,946
  • 7
  • 29
  • 56
  • there is also `IList` – Default May 24 '13 at 06:30
  • Please check this post http://stackoverflow.com/questions/271710/collectiont-versus-listt-what-should-you-use-on-your-interfaces – Kurubaran May 24 '13 at 06:34
  • Could you motivate why you believe that this is not a duplicate of the other question? – Default May 24 '13 at 07:50
  • The [IList](http://msdn.microsoft.com/en-us/library/5y536ey6.aspx) interface inherits `ICollection` and declares `Add`, `Insert`, `Remove` methods and similar. `AddRange` is not included in `IList`, but for these occasions you could perhaps do explicit casting? Alternatively, you could implement an `AddRange(this IList destination, IEnumerable source)` extension method to hide the casting. – Anders Gustafsson May 24 '13 at 09:57

1 Answers1

2

exposing List is not a good practice because you can modify original collection with methods like Add, is better to expose IEnumerable this interface will not allow to change collection, the my advantage of this you will keep logic with managing your collection in one place

Serghei
  • 3,748
  • 2
  • 18
  • 33
  • `ICollection` and `IList` do guarantee though that there is an actual collection in memory. An `IEnumerable` might also be a wrapper for a database cursor or a file and therefore be very slow or unstable to iterate. I agree with you that exposing `IEnumerable` is often elegant, but not *always* the best choice IMHO. Some languages have built-in immutable collections, and there are some available for C# too. http://blogs.msdn.com/b/bclteam/archive/2012/12/18/preview-of-immutable-collections-released-on-nuget.aspx – Matthias Meid May 24 '13 at 07:37
  • 3
    "exposing List is not a good practice because you can modify original collection": This isn't the reason FxCop recommends not to expose `List`: the usual alternative `IList` is accepted by FxCop and also allows you to modify the collection, if the underlying concrete collection is mutable (`IsReadOnly` false). For that matter, returning `IEnumerable` doesn't protect against casting and modifying a mutable underlying collection. If you want to return an immutable collection, you can return `ReadOnlyCollection` or similar, cast to `IList`, `IEnumerable` or `ICollection` – Joe May 24 '13 at 07:38