8

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?

2
  • 1
    generics one provides compile type safety Commented Dec 29, 2015 at 16:18
  • 2
    Generics were a later addition to the framework. In general it means you can work with typed collections, rather than collections of objects. Commented Dec 29, 2015 at 16:19

1 Answer 1

17

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, now I am able to understand it more clearly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.