Check if C# object is an array and iterate over it


Sometimes, you want to know if an object is an array. One way to do it is

if (obj.GetType().IsArray) {
  ...
}

Another way you can do it is

if (obj is Array) {
  ...
}

The advantage of using the Array type is that you can iterate over an array without bothering about the type of the objects it holds

foreach (object o in (Array)obj)
{
  ...
}

To set the value at a particular array index, iterate using a for loop

for (int i = 0; i < ((Array)obj).Length; i++)
{
  ((Array)obj).SetValue(someval, i);
}

To wrap it up, obtain the type of the elements of an array thus

obj.GetType().GetElementType()

One thought on “Check if C# object is an array and iterate over it

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s