Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the type of object in ArrayList

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

like image 909
mouthpiec Avatar asked Mar 15 '10 08:03

mouthpiec


3 Answers

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

if( obj.GetType() == typeof(int) )
{
    // int
}
like image 109
balexandre Avatar answered Sep 25 '22 01:09

balexandre


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");
        }
    }
like image 32
Paolo Tedesco Avatar answered Sep 24 '22 01:09

Paolo Tedesco


Use GetType() to know the type of Object.

like image 3
Gopi Avatar answered Sep 22 '22 01:09

Gopi