How to cast Boolean[] to Object[]

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
 
M

Mattias Sjögren

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top