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?
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.
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.
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With