Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Difference between List<T> and Collection<T> (CA1002, Do not expose generic lists) [duplicate]

Tried to run Run Code Analysis on a project here, and got a number of warnings that said something like this:

CA1002 : Microsoft.Design : Change 'List<SomeType>' in 'SomeClass.SomeProtectedOrPublicProperty' to use Collection, ReadOnlyCollection or KeyedCollection

Why should I use Collection<T> instead of List<T>? When I look at the msdn documentation, they seem almost equal. After reading the error help for the warning, I found that

System.Collections.Generic.List(T)_is a generic collection designed for performance not inheritance and, therefore, does not contain any virtual members.

But what does this really mean? And what should I be doing instead?

Should I keep using List<T> internally, and then in the properties return a new Collection<T>(someList) instead? Or should I just start using Collection<T> instead of List<T>?

like image 246
Svish Avatar asked Aug 05 '09 09:08

Svish


People also ask

Bahasa C digunakan untuk apa?

Meskipun C dibuat untuk memprogram sistem dan jaringan komputer namun bahasa ini juga sering digunakan dalam mengembangkan software aplikasi. C juga banyak dipakai oleh berbagai jenis platform sistem operasi dan arsitektur komputer, bahkan terdapat beberepa compiler yang sangat populer telah tersedia.

C dalam Latin berapa?

C adalah huruf ketiga dalam alfabet Latin. Dalam bahasa Indonesia, huruf ini disebut ce (dibaca [tʃe]).

Bahasa C dibuat pertama kali oleh siapa dan tahun berapa?

Bahasa pemrograman C ini dikembangkan antara tahun 1969 – 1972 oleh Dennis Ritchie. Yang kemudian dipakai untuk menulis ulang sistem operasi UNIX. Selain untuk mengembangkan UNIX, bahasa C juga dirilis sebagai bahasa pemrograman umum.


1 Answers

In short, the generic list does not have virtual methods for Add, Remove etc, as it was designed to be fast, not extensible. This means that you cannot swap this concrete implementation out for a useful subclass (even though you can subclass it as it is not sealed).

Therefore, by exposing the List itself, you can never extend your collection to track add or remove operations (for example) without breaking the public contract of the class.

By exposing your collection as an IList or some-such, you can still use the List as the actual backing-store, but you retain future extensibility as you can swap out the concerete implementation later without changing the public contract of your class.

like image 75
Rob Levine Avatar answered Oct 06 '22 03:10

Rob Levine