views:

236

answers:

4

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

+2  A: 

use GetType() to know the type of Object

Sri Kumar
+8  A: 

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");
        }
    }
}
Paolo Tedesco
+1  A: 

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.

Guffa
It would be better to extract value from the list using indexer only once and then cast it to the necessary type.
Andrew Bezzub
@Andrew: Yes, that is correct. I wrote the example to demonstrate the type recognition and casting, it's not optimal in other aspects.
Guffa
+1  A: 

you can use the normal GetType() and typeof()

if( obj.GetType() == typeof(int) )
{
    // int
}
balexandre