5

I have read at couple of places that, a generic collection class in the System.Collections.Generic namespace should be used instead of classes such as ArrayList in the System.Collections namespace. I am not able to understand, how is it better, as both are collection?

daisy
  • 277
  • 1
  • 5
  • 16

1 Answers1

15

Generic collection types allow strongly typing your collections. Take for example this ArrayList, which we want to contain dogs:

ArrayList a = new ArrayList();
a.Add(new Dog());

If you want to get the first item out, you need to cast the result, since Dog d = a[0]; doesn't work. So we do this:

Dog d = (Dog)a[0];

but the compiler also allows this:

Cat c = (Cat)a[0];

Generics allow you to do this:

List<Dog> a = new List<Dog>();
a.Add(new Dog());

Dog d = a[0];

See! No casting. We don't have to help the compiler understand there can only be dogs inside that list. It knows that.

Also, this won't compile:

Cat c = a[0];

So: no boxing and unboxing, no runtime errors because there is a wrong cast. Type safety is a blessing for programmers and users. Use generic collections as much as you can, and only use non-generic collections if you have to.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325