Hi,
Is there a way to get the type of object in the arraylist?
I need to make an IF statment as the following (in C#):
if(object is int)
//code
else
//code
thanks
Hi,
Is there a way to get the type of object in the arraylist?
I need to make an IF statment as the following (in C#):
if(object is int)
//code
else
//code
thanks
What you are doing is fine:
static void Main(string[] args) {
ArrayList list = new ArrayList();
list.Add(1);
list.Add("one");
foreach (object obj in list) {
if (obj is int) {
Console.WriteLine((int)obj);
} else {
Console.WriteLine("not an int");
}
}
}
That's pretty much how you do it:
if (theArrayList[index] is int) {
// unbox the integer
int x = (int)theArrayList[index];
} else {
// something else
}
You can get a Type object for the object, but then you should make sure that it's not a null reference first:
if (theArrayList[index] == null) {
// null reference
} else {
switch (theArrayList[index].GetType().Name) {
case "Int32":
int x = (int)theArrayList[index];
break;
case "Byte":
byte y = (byte)theArrayList[index];
break;
}
}
Note that unless you are stuck with framework 1.x, you shouldn't use the ArrayList
class at all. Use the List<T>
class instead, where you should use a more specific class than Object
if possible.
you can use the normal GetType() and typeof()
if( obj.GetType() == typeof(int) )
{
// int
}