By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,195 Members | 1,468 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,195 IT Pros & Developers. It's quick & easy.

Reflection & Array Properties

P: n/a
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 :)

Feb 1 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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?
Feb 1 '07 #2

P: n/a
Velislav <vg*****@gmail.comwrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 1 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.