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?
- 1generics one provides compile type safetyEhsan Sajjad– Ehsan Sajjad2015-12-29 16:18:50 +00:00Commented Dec 29, 2015 at 16:18
- 2Generics were a later addition to the framework. In general it means you can work with typed collections, rather than collections of objects.James Thorpe– James Thorpe2015-12-29 16:19:04 +00:00Commented Dec 29, 2015 at 16:19
1 Answer
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.