Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What advantage do you get with a collection over List(Of T) in .NET 2.0+

I had another developer ask why I use List all over the place ... and I thought about it for a minute ... and couldn't come up with a definitive answer.

If you inherit from the collection base class to extend instead of using List(Of T) - what advantages do you get? Or - what don't you get with List?

like image 566
Toran Billups Avatar asked Jan 30 '09 14:01

Toran Billups


People also ask

What is difference between collection and List in C#?

Collection is a modifiable set. You can add and remove objects from the set, you can also get the count of items in the set. But there still is no order, and because there is no order: no way to access an item by index, nor is there any way to sort. List is an ordered set of objects.

What is the difference between a List and a collection?

In List, data is in particular order. In Set, it can not contain the same data twice. In Collection, it just stores data with no particular order and can contain duplicate data.

Why does adding a new value to List <> overwrite previous values in the List <>?

Essentially, you're setting a Tag's name to the first value in tagList and adding it to the collection, then you're changing that same Tag's name to the second value in tagList and adding it again to the collection. Your collection of Tags contains several references to the same Tag object!

What is using System collections generic in C#?

System.Collections.Generic ClassesIt stores key/value pairs and provides functionality similar to that found in the non-generic Hashtable class. It is a dynamic array that provides functionality similar to that found in the non-generic ArrayList class.


2 Answers

Generic List gives you performance boost.

See this question:

Do C# Generics Have a Perfomance Benefit?

Quote from MSDN:

It is to your advantage to use the type-specific implementation of the List<(Of <(T>)>) class instead of using the ArrayList class or writing a strongly typed wrapper collection yourself. The reason is your implementation must do what the .NET Framework does for you already, and the common language runtime can share Microsoft intermediate language code and metadata, which your implementation cannot.

like image 182
aku Avatar answered Sep 22 '22 18:09

aku


List is not thread safe, and not meant to be exposed. You can use a Collection(Of T) instead (note that this is different from CollectionBase), or simply expose IList(Of T) or IEnumerable(Of T).

like image 24
Jon B Avatar answered Sep 24 '22 18:09

Jon B