how to add to an Array?

  • Thread starter Thread starter typeMisMatch
  • Start date Start date
T

typeMisMatch

Hi,

This may sound simple, here is my problem.

I have a couple classes, Class1, Class2, Class3.

Class1 has a collection of Class2 and Class3. Right now those collections
are defined as ArrayLists. This is a problem because when you reference them
eg: Class1.Class2s[index] you just get an Object because this is an
ArrayList as opposed to an Array of Class2.

So this means I have to do ((Class2)Class1.Class2s[index]).Method which
really sux. Now, if I make Class2s an Array such as Class2[], there is no
Add method to extend the array collection?

What is a good method of having a collection which is extendable but of a
particular type?

thanks

-c
 
You have three choices that I can think of offhand.

First option is to check out the System.Collections.Specialized namespace to
see if there's anything there that happens to fit your needs. There is for
instance a StringCollection class that is a wrapper around ArrayList that
provides what amounts to an ArrayList of strings, strongly typed. The
casting overhead is still there, but the implementation is hidden and you
don't have to worry about it in your own code.

Second option is to write a class that inerits from CollectionBase and do
the implementation for the type you want to store in the collection. This
gives you an Add() method and so forth as you'd expect.

Third option is to use VS 2005 beta or C# Express 2005 beta and use the
System.Collections.Generic namespace. For example, the Generic.List class
is a replacement for ArrayList:

List<int> list = new List<int>();
list.Add(27);
list.Add(243);
Console.WriteLine("Second element: {0}",list[1]);

It works just the same as ArrayList but is strongly typed, and there's no
casting, hidden or otherwise.

--Bob
 
Back
Top