Reputation: 8462
I have a dynamic
object that sometimes is an object
and sometimes is an object[]
.
How can I check if the dynamic object is an array?
Upvotes: 18
Views: 17943
Reputation: 508
To complement Rango's original response, a more generic way to determine is to use the type's IsSerializable property. Because if the object is a List or any other collection, the IsArray returns false.
int [] array = {1,2,3,4};
Type t1 = array.GetType();
// t1.IsArray == true
List<int> list = new List();
list.AddRange(array);
Type t2 = list.GetType();
//t2.IsArray = false;
//t2.IsSerializable = true;
foreach(var i in list) {
// do stuff
}
Upvotes: 0
Reputation: 3451
Why not just 'is' operator (I just did quick test on immediate windows of Visual Studio debugger), and it works. but not sure if Tim's answer is optimal.
void foo(object o)
{
if( o is System.Array)
{
//its array
}
}
Upvotes: 7
Reputation: 460048
Use Type.IsArray
:
From MSDN:
int [] array = {1,2,3,4};
Type t = array.GetType();
// t.IsArray == true
Console.WriteLine("The type is {0}. Is this type an array? {1}", t, t.IsArray);
Upvotes: 32