Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a reflected type is an array

I'm using reflection to read in an xml file and keep coming across an error telling me that I cannot convert a string to a string[] (which I don't want to do!) I think the cause of my problem is I'm unable to tell if the type of the object is an array or not. Below is what I'm currently using (doesn't work right) but I've also tried to use if(mi[i].GetType() == typeof(string[])) which also doesnt work..

MemberInfo[] mi = objType.GetProperties();
for (int i = 0; i < mi.Length; i++)
{
  if (mi[i].GetType().IsArray)
  {
  }
  else
  {
   //Code path is running through here
  }

The file is read in correctly..

EDIT: I thought I'd better add the structure to my objType to better explain..

objType is a class that contains a string[] variable that in this case is referred to as mi[i]

like image 840
Sayse Avatar asked Sep 18 '25 09:09

Sayse


1 Answers

You need to use PropertyType rather than GetType() on the MemberInfo to get the underlying type of the property.

var mi = objType.GetProperties();
for (int i = 0; i < mi.Length; i++)
{
    var type = mi[i].PropertyType;
    //Check for string array
    if (type.IsArray && type.GetElementType() == typeof(string))
    {
    }
}

Or you can do

if(type == typeof(string[]))
{
}
like image 160
Magnus Avatar answered Sep 19 '25 23:09

Magnus