Click to See Complete Forum and Search --> : array again


peevee12
July 1st, 2004, 07:59 AM
what should I do if i want to insert a object type variable in an string array?

torrud
July 1st, 2004, 09:43 AM
If that object is a string do a type cast.
If not forget your string array and take an ArrayList. There you can store objects and strings are objects too.

Andy Tacker
July 2nd, 2004, 06:52 AM
yeh, torrud is right.
use arraylist which will ease the storage.
when you need to retrieve simply cast the output to the desired one.

Ravenz
July 4th, 2004, 04:20 PM
:0)

using System.Collections; // For ArrayList Enabled

ArrayList myList = new ArrayList;
myList.Add("This is a string");
myList.Add(3453);

string myString = (string)myList[0];
int myInt = (int)myList[1];


Happy coding! :)

darwen
July 4th, 2004, 05:02 PM
Be careful with ArrayList.

It's not typesafe, so you can store anything in it.

I recommend having a seperate class which has an array list as a member variable to make sure you don't accidentally add something wrong to it.

Either that or do this :


ArrayList aList;
aList.Add("Hello");
aList.Add(200);

// put a try catch for this

string sItem = null;

try
{
sItem = aList[0] as string;
}
catch (InvalidCastException)
{
// you know now that it wasn't a string
}



Otherwise you might get caught out !

Darwen.