Generics + collections

  • Thread starter Thread starter Chris S.
  • Start date Start date
C

Chris S.

Am I correct in thinking that C#/.NET 2.0 removes the need for a
collection for each business object you have, and allows you to create
just one collection?

Or is this just the equivalent of using Object for your collection?
 
Chris,

..NET eliminates the need of creating strongly typed collection for each
business object. You can use generic collection and benefit from the stronlg
typness.

Using generics is not equivalent of having collection of Object.
Using ArrayList for example, which is collection of Object one can create
heterogeneous collection, which is not possible with generic collection
unless the type is not sepcified as Object.
 
I can see mountains of source code being removed in business layers
thanks to this. I realise that compile time errors occur if you create
a collection with a type and then try to use another type, e.g.

MyCollection<MyObject> coll = new MyCollection<MyObject>();
coll.Add(new MyObject());
coll.Add("test");

but what I meant was internally, there can't be a huge difference
between an Object being passed around?
 
Chris S. said:
I can see mountains of source code being removed in business layers
thanks to this. I realise that compile time errors occur if you create
a collection with a type and then try to use another type, e.g.

MyCollection<MyObject> coll = new MyCollection<MyObject>();
coll.Add(new MyObject());
coll.Add("test");

but what I meant was internally, there can't be a huge difference
between an Object being passed around?

Most people wouldn't have bothered creating typesafe collections for
internal use only - that's usually reserved for where you have collection
valued public properties.

Before you go and automatically change all your code watch out for the fact
that generic collections are not totally backward compatible - eg. IList<T>
does not derive from IList.

Note also that List<any struct> is more efficient than ArrayList of the
struct because of boxing
 
There is; when you put something into an ArrayList, its up cast to
object when its added, and has to be down cast when you pull it out.
That takes time. Worse, value types have to be boxed and unboxed,
adding even more time. A generic collection won't have these problems
(unless as someone else mentioned, you have a generic collection of
objects).
 
Back
Top