Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I replace CollectionBase with Generics?

I'm not looking for how, I'm looking for why? I couldn't find a straight forward answer to this.

like image 715
Dilbert789 Avatar asked Mar 05 '10 20:03

Dilbert789


People also ask

Why do we need generic collection?

A generic collection is strongly typed (you can store one type of objects into it) so that we can eliminate runtime type mismatches, it improves the performance by avoiding boxing and unboxing.

Why We Use Using system collections generic in C#?

Contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and performance than non-generic strongly typed collections.

What is difference between generic and non-generic in C#?

The key difference between Generic and Non-generic Collection in C# is that a Generic Collection is strongly typed while a Non-Generic Collection is not strongly typed.

What is difference between collection and generics in C#?

Better Performance with Generics As you have seen in the above example, at the time of fetching the data from the ArrayList collection we need to do type casting which causes performance degrades. But at the time of fetching the data from the generic List, we don't require to do type casting.


2 Answers

Yes. CollectionBase was a previous attempt, and a way to provide type safety.

Generics give you these advantages, but add two more HUGE advantages:

  1. With generics, you no longer have boxing and unboxing at every access to your collection. This provides a huge perf. advantage.
  2. 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:

  1. Using generic collections will allow you to directly use LINQ to Objects on your collections, without requiring calls to Cast<T> (CollectionBase does not implement IEnumerable<T>, only IEnumerable).
  2. Provide consistency with any new code, which should always be done using the new generic collections.
like image 180
Reed Copsey Avatar answered Sep 30 '22 16:09

Reed Copsey


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.

like image 30
Donald Byrd Avatar answered Sep 30 '22 15:09

Donald Byrd