How to cast Boolean[] to Object[]

  • Thread starter Thread starter fj
  • Start date Start date
F

fj

I use reflection to get a property from an object. The property is always an
array of a basic datatype. I only care about the first item and get the
string value.

//obj is the object I want to get a property value from.
Type type = obj.GetType();
PropertyInfo propertyInfo = type.GetProperty(propertyName);

Object propertyObj = propertyInfo.GetValue(obj, null);

Object[] tempObj = (Object[])propertyObj;

string strResult = tempObj[0].ToString();

There is no problem for propertyObj when it's an int or string array.
However, when it's a boolean[] an InvalidCastException is thrown.:

Unable to cast object of type System.Boolean[] to type System.Object[]

I am using an awkward way to get by. I am looking for a better way to take
care of the case.

TIA

-fj
 
I am using an awkward way to get by. I am looking for a better way to take
care of the case.

Array tempObj = (Array)propertyObj;
string strResult = tempObj.GetValue(0).ToString();

should work for any one dimensional array.


Mattias
 
Back
Top