Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Collections.Generic vs System.Collections? [duplicate]

Tags:

c#

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?

like image 223
daisy Avatar asked Dec 29 '15 16:12

daisy


1 Answers

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.

like image 111
Patrick Hofman Avatar answered Oct 16 '22 16:10

Patrick Hofman