Reflection & Array Properties

V

Velislav

Hi, I've got the following piece of code:

string GetPropertyValue(object jobCard, string propertyName,
int index)
{
PropertyInfo property =
jobCard.GetType().GetProperty(propertyName);
if (property.PropertyType.IsArray)
{
object[] propertyValue =
(object[])property.GetValue(jobCard, null);
return propertyValue[index].ToString();
}
else
{
return property.GetValue(jobCard, null).ToString();
}
}

all it does is take an object (jobCard), and returns a string
representation of the given property (propertyName). If that property
is an array, it returns the value of the array item at the specified
index (index).

the jobCard parameter is a reference to an object of class JobCard
which looks something like this:

public class JobCard
{
...
int[] specification;
RawMaterial[] rawMaterials;
...
int[] Specification { get { return specification; } set
{ specification = value; } }
RawMaterial[] RawMaterials { get { return rawMaterials; } set
{ rawMaterials = value; } }
...
}

the following happens when i invoke my method:
GetPropertyValue(jobCard, "RawMaterials", 1); // Works 100%
GetPropertyValue(jobCard, "Specification", 1); //Error: Unable to cast
object of type 'System.Int32[]' to type 'System.Object[]'.

Note: Both the RawMaterial[] and int[] arrays contain an element with
index 1.

obviously the error is thrown when i cast the result of
PropertyInfo.GetValue()... but I see no reason why I shouldn't be able
to cast int[] to object[]
Any ideas?

Thanks :)
 
V

Velislav

I found a solution:
by casting the result of the PropertyInfo.GetValue() to Array, it
seems to work...
ie Array propertyValue =
(Array)property.GetValue(jobCard, null);
return propertyValue.GetValue(index).ToString();

still curious about the initial cast though... surely all types can be
cast to object?
 
J

Jon Skeet [C# MVP]

Velislav said:
I found a solution:
by casting the result of the PropertyInfo.GetValue() to Array, it
seems to work...
ie Array propertyValue =
(Array)property.GetValue(jobCard, null);
return propertyValue.GetValue(index).ToString();

still curious about the initial cast though... surely all types can be
cast to object?

Yes, but you can't cast from int[] to object[]. Basically, while
reference type arrays are covariant, value type arrays aren't.
 

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