473,660 Members | 2,459 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reflection & Array Properties

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

string GetPropertyValu e(object jobCard, string propertyName,
int index)
{
PropertyInfo property =
jobCard.GetType ().GetProperty( propertyName);
if (property.Prope rtyType.IsArray )
{
object[] propertyValue =
(object[])property.GetVa lue(jobCard, null);
return propertyValue[index].ToString();
}
else
{
return property.GetVal ue(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:
GetPropertyValu e(jobCard, "RawMateria ls", 1); // Works 100%
GetPropertyValu e(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.Ge tValue()... but I see no reason why I shouldn't be able
to cast int[] to object[]
Any ideas?

Thanks :)

Feb 1 '07 #1
2 10454
I found a solution:
by casting the result of the PropertyInfo.Ge tValue() to Array, it
seems to work...
ie Array propertyValue =
(Array)property .GetValue(jobCa rd, null);
return propertyValue.G etValue(index). ToString();

still curious about the initial cast though... surely all types can be
cast to object?
Feb 1 '07 #2
Velislav <vg*****@gmail. comwrote:
I found a solution:
by casting the result of the PropertyInfo.Ge tValue() to Array, it
seems to work...
ie Array propertyValue =
(Array)property .GetValue(jobCa rd, null);
return propertyValue.G etValue(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.co m>
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1617
by: Angelos Karantzalis | last post by:
Hi y'all ... I've just come across a rather weird problem. i'm using the following code to get the names of the public properties of an object: public static string GetPropertyNames(object instance){ Type objType = instance.GetType(); PropertyInfo props = objType.GetProperties();
27
3824
by: Daniel Vallstrom | last post by:
I'm having problems with inconsistent floating point behavior resulting in e.g. assert( x > 0.0 && putchar('\n') && x == 0.0 ); holding. (Actually, my problem is the dual one where I get failed assertions for assertions that at first thought ought to hold, but that's not important.) At the end is a full program containing the above seemingly
10
7360
by: Sunny | last post by:
Hi, I have an old problem which I couldn't solve so far. Now I have found a post in that group that gave me an idea, but I can not fully understand it. The problem is: I'm trying to use a Windows.Forms.UserControl in a COM environment, i.e. I want to host that control in a COM host. So far, so good, I can host it, but I can not reach the parent COM object from the control (Parent property is null :( ). I have stopped the control in the...
2
6756
by: Shmuel Cohen | last post by:
I have a class holding some enumerated types, i.e., public class MyEnums { public enum DATA_ITEM {FIRST, SECOND, THIRD,FOURTH,FIFTH}; ... } And I have a class the contains data, for example:
2
2872
by: Marc | last post by:
Given a class 'Invoice' with a property 'public IMyColl<IInvoiceLine> InvoiceLines' where 'IMyColl<T> : IList<T>' i would like to detect by reflection that 'InvoiceLines' is a 'System.Collection.Generic.IList'. When performing something like: 'if (typeof(IList<>).IsAssignableFrom(propertyInfo.Type))' where 'propertyInfo' obviously refers to the 'InvoiceLines', the result is always 'false' because indeed 'IList<object>' and...
3
1107
by: Dennis | last post by:
I pass an array that consists of elements each of an unknown class to a function. I want to get a list of the properties of the unknown class and the value for each property for each element of the array. How would I do this. I tried propertyDescriptionclass but got an error saying I needed to use late binding. -- Dennis in Houston
8
292
by: Rlrcstr | last post by:
If I have some code behind a form and I want to be able to pass an object to it... any of several user defined classes that I have... and then display the values in the member variables of the class, I'm guessing that I use Reflection. I have never used anything like that before. Can someone point me to a good example of doing this? I will basically be drawing a table on the form with dta from the passed class in columns. The...
0
2025
by: liko81 | last post by:
I have an Invoice class that must know, directly or indirectly, how to do anything associated with creating, reading, or otherwise processing an invoice to a customer. It is an uber-DAO object that combines the business logic and DAO layers. The invoice it handles can have one to many lines. The most logical implementation is an Invoice object with an array of InvoiceLine objects. We of course want to prevent Joe Programmer from directly...
7
16558
by: Tom Dacon | last post by:
I'm using Reflection to iterate over the properties and fields of an arbitrary object. For non-indexed properties it's pi.GetValue(theObject, Nothing) for VB, or pi.GetValue(theObject, null) for C# For indexed properties, instead of Nothing (null) you pass an array of index values. OK, no problem so far.
0
8428
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8341
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8751
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8539
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
5650
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4176
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
1982
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1739
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.