C# Collections – Non-generic or Generic?

Non-generic- vs generic collections

When coding in C# you will pretty soon encounter Collections (Lists, Queues, Stacks, and so on). As soon as you wish to use a Collection of some sort you will have the choice of using one from the System.Collections namespace or one from the System.Collections.Generic namespace. The most commonly used Collection is the List and the non-generic version of List is the ArrayList.

Using the non-generic version forces you to cast the objects into the correct type.

ArrayList l = new ArrayList { new MyType() };
// MyType t = l[0]; This won't compile
MyType t = (MyType)l[0]; // But this will
MyOtherType t2 = (MyOtherType)l[0]; // Unfortunately this will also compile

As can be seen in the code above the non-generic ArrayList is error prone. There is no compile time check whether you mistakenly cast to the correct type or not. The generic version of ArrayList is List<T>. Using this forces you to define the type of objects the list will contain already when creating the list, and the static code analysis tools and compiler will give you errors if you misuse the type.

var l = new List<MyType> { new MyType() };
MyType t = l[0]; // Now this compiles fine
MyType t2 = (MyType)l[0]; // This also works fine, but the cast is not needed
// MyOtherType t3 = (MyOtherType)l[0]; This won't compile

So, no unboxing and boxing, no need to help the compiler understand what types of objects the list holds, no runtime errors due to incorrect casts.

Now, List is only one of many Collection types in the System.Collections.Generic namespace, you will find generic versions of all the non-generic Collections. My advice is to simply pretend that the non-generic Collection types doesn’t even exist, and use the generic ones, always.

Lämna en komentar

E-postadressen publiceras inte. Obligatoriska fält är märkta *