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
you can use the normal GetType() and typeof()
if( obj.GetType() == typeof(int) )
{
// int
}
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");
}
}
Use GetType()
to know the type of Object
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With