I'm not looking for how, I'm looking for why? I couldn't find a straight forward answer to this.
Type safety without having to write a lot of code per-type. If you look at the example in the MSDN CollectionBase documentation, you have to write a lot of boiler-plate code to make a typesafe collection of Int16. With generics it's somewhat shorter:
var myListofInt16 = new List<Int16>();
Every bit of code you don't have to write is code that you won't get wrong (I say that because it applies to me, I'm sure it applies to others too! ;-)
With CollectionBase you need to extend to provide the functionality that generics do natively. You have to write in all the plumbing to account for type safety in sub classes that you create from it. With generics there is no need to. Do you need to convert to generics? That depends on your situation, but I wouldn't use it going forward.
Plus, using generics instead of collection base gives you all the extension methods written into .net to make common tasks easier. MS is pushing the use of generics and has actively developed their adoption. They will most likely continue to develop their functionality.
Strongly typed access to all the different kinds of collections at the cost of only typing <type>
?
EDIT: If you are removing existing and working code, the only reason would be for performance as mentioned elsewhere.
Yes. CollectionBase was a previous attempt, and a way to provide type safety.
Generics give you these advantages, but add two more HUGE advantages:
- With generics, you no longer have boxing and unboxing at every access to your collection. This provides a huge perf. advantage.
- With generics, you can use a single implementation for all of your types. With CollectionBase, each type required a custom implementation, which leads to a huge amount of duplicated code (ie: potential for bugs).
Edit:
I thought of a couple of other compelling reasons to move your code to using generic collections:
- Using generic collections will allow you to directly use LINQ to Objects on your collections, without requiring calls to
Cast<T>
(CollectionBase does not implementIEnumerable<T>
, onlyIEnumerable
). - Provide consistency with any new code, which should always be done using the new generic collections.
You want to use Generics to avoid boxing.
This is a good article listing the Benefits of Generics.
There's another reason.
LINQ.
You can only use LINQ methods on a collection that implements IEnumerable<T>
.
To use LINQ on a CollectionBase
, you must either call Cast<T>
first, or manually implement IEnumerable<T>
on the class.
By inheriting from ObjectModel.Collection<T>
, you get an IEnumerable<T>
implementation for free.