17

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

4 Answers 4

33

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

if( obj.GetType() == typeof(int) )
{
    // int
}
Sign up to request clarification or add additional context in comments.

Comments

16

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");
        }
    }
}

If you were checking for a reference type instead of a value type, you could use the as operator, so that you would not need to check the type first and then cast:

    foreach (object obj in list) {
        string str = obj as string;
        if (str != null) {
            Console.WriteLine(str);
        } else {
            Console.WriteLine("not a string");
        }
    }

Comments

3

Use GetType() to know the type of Object.

Comments

1

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.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.