Where can I learn about the various types of .NET lists?

前端 未结 10 1120
南笙
南笙 2020-12-12 13:13

Does anyone know a good resource to concisely explain the different types of lists available in C# and when their usage is appropriate?

For example, List, Hashtable,

10条回答
  •  情书的邮戳
    2020-12-12 14:02

    You should pick up a book about basic data structures. It's the same theory regardless of language.

    A short explanation:

    • Array: (as in e.g. int[] myArray) - static array that can be used when the collection never changes (you can't add or remove items in it, but you can change the values of individual items)
    • ArrayList: general purpose array/list that allows relatively fast enumeration aswell as direct access. This list can grow automatically as you add items, but since it only stores Object, you should seldom use it due to performance and type-safety issues.
    • List: Generic version of the above ArrayList. It provides a nice balance between performance and flexibility and should be used almost always when you have a dynamic flat list of items. (New in .NET 2.0)
    • Hashtable: Works like a flat list but instead of indexing it with integers, it can be indexed using any object. Worth noting is that there is no "order" in a hash table.
    • Dictionary: Generic version of the Hashtable. Use this in .NET 2.0 and higher instead of the Hashtable for the same reasons as with ArrayList vs List above.
    • Stack: Provides a first-in last-out type of list. The item you added last will be the item you receive first when you pick something out.
    • Queue: Provides a first-in first-out list. Think of it as a tube, where you insert items at one end and pick them out in the other end. Typically used to pass messages between e.g. threads.

    In general, you should use the generic collections for almost everything you do in .NET 2.0 and higher. You will get full type-safety (compared to e.g. ArrayList and HashTable) and they are much faster for value types (integers, structs, floats etc.) compared to non generic onces.

    If you have a list of items that will never change, or you don't need/want the flexibility of List you can of course use an array since it has the least amount of overhead of them all.

    A recommendation when you return a collection from a public method or property is to cast it to a less flexible interface. So if you have a List that you return, you could cast it to an IEnumerable which means that your consumer cannot add items to it (unless of course it casts it back, but its still an indication to the users). Casting it will also give you the flexibility to change the underlying datastructure later, while maintaining the API stability. You could also pick ICollection or IList to expose a bit more functionality but keeping the actual data structure hidden.

提交回复
热议问题