what should I do if i want to insert a object type variable in an string array?
Printable View
what should I do if i want to insert a object type variable in an string array?
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.
yeh, torrud is right.
use arraylist which will ease the storage.
when you need to retrieve simply cast the output to the desired one.
: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! :)
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 :
Otherwise you might get caught out !Code: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
}
Darwen.