Thread: Array question
View Single Post
Old Jan 4th, 2007, 11:14 PM   #9
lectricpharaoh
Caffeinated Neural Net
 
lectricpharaoh's Avatar
 
Join Date: Jun 2005
Location: Wet west coast of Canada
Posts: 1,126
Rep Power: 5 lectricpharaoh will become famous soon enough
I guess this is what I get for not being so active here lately, as both my suggestions have already been made.

@Arla: If you have a fixed relationship between the types, for example, a 'unit' of data is composed of a string, an int, and a long, then structs (or classes) are definitely the way to go. If you won't know the types beforehand, then you can do what Tim suggested, and stuff everything into a collection (array or otherwise) of objects. Then, you can use the GetType() method to determine the type at runtime, and process it as appropriate. To get the type at compile time, use the typeof operator. For example, assume you've stuffed in a bunch of elements into an array. You could probably do something like this:
for(int x=0; x<array.length; ++x)
{
  if(array[x].GetType() == typeof(string))
    Console.WriteLine("Type is string");
  else if(array[x].GetType() == typeof(int))
    Console.WriteLine("Type is int");
  else if(array[x].GetType() == typeof(long))
    Console.WriteLine("Type is long");
}
Obviously, instead of simply outputting a message, you'll want to do appropriate processing, but hopefully, you get the idea. This shows that you can (in a manner) have an array with elements of different types. Strictly speaking, this is not true, as every element is of type object (or whatever the base class in question is; you needn't go quite that far up the object hierarchy in all cases). Remember that an object of a subclass is also an object of the parent class (a Car is also a Vehicle), but the inverse is not necessarily true. Thus, there is the test to see which exact subclass the element is, in order to process it properly.

If you're curious, you can also use the GetMethods(), GetMembers(), and GetProperties() methods of the System.Type class (both GetType() and typeof return a System.Type, so you can call these methods on the returned object). The last one is especially handy (it's an integral part of the mechanism through which certain data-bound controls can determine the various fields- ie, columns- to display). This page gives further details.
__________________
And once again, Probability proves itself willing to sneak into a back alley and service Drama as would a copper-piece harlot.
- Vaarsuvius, Order of the Stick
lectricpharaoh is offline   Reply With Quote