Thread: Array question
View Single Post
Old Jan 3rd, 2007, 8:05 PM   #7
Tim
Unverified User
 
Join Date: Dec 2006
Location: Bristol UK
Posts: 19
Rep Power: 0 Tim is on a distinguished road
If you have an array of object you can put anything you want into the array

The problem comes when you want to get data out, you have to know the type that the data was before it went into the array and was cased to type object.

C# is a statically typed langage so you cant just have a variable that is everything to everyone. It also is dynamically type checked so if you try to make a string do something that only an integer can do it will fail.

	object[] myArray = new object[10];
	myArray[0] = 20;
	myArray[1] = "Hello World";
	myArray[2] = 3.14;
	
           //The cast must be correct here.		
	int i = (int)myArray[0];
	string s = (string)myArray[1];
	double d = (double)myArray[2];

This probably wont solve your problem as i think you want it so you can put anything in and then get it out without knowing what it was to start with.

edit: If you look into reflection you may be able to tell the type for the element at runtime and so have the correct cast.
Tim is offline   Reply With Quote