Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio Code Analysis Rule - "Do not expose generic lists"

Do not expose generic lists

IF all my methods, need to expose a collection, then I need to user the Linq Extension .ToList(), almost everywhere I need to use lists, or user Collections in all my code.

If that’s the case, .ToList() is ignoring the rule right? Or is there a technique like copying the list o something to fix the violation and still return a list?

like image 777
Fraga Avatar asked Jun 15 '10 14:06

Fraga


People also ask

How do you fix ca1002 do not expose generic lists?

To fix a violation of this rule, change the System. Collections. Generic. List<T> type to one of the generic collections that is designed for inheritance.

Should I use collection or List c#?

The reason "why" you "should" use a Collection<T> instead of a List<T> is because if you expose a List<T> , then anyone who gets access to your object can modify the items in the list. Whereas Collection<T> is supposed to indicate that you are making your own "Add", "Remove", etc methods.


1 Answers

I disable that rule because I don't feel like it's a valid one. If you want to return a collection which contains an O(1) count and is not a direct reference to an internal field, List<T> is the best choice.

I don't deeply understand your case here but it sounds like you have a method which returns a LINQ query over some internal data. If that's the case then using a .ToList() on the data is appropriate since you likely don't want future modifications of your internal fields to affect the return value of a method. In that case, there is no reason to not expose it as a List<T>.

like image 71
JaredPar Avatar answered Oct 21 '22 00:10

JaredPar