473,324 Members | 2,356 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

Using reflection to access array elements

Hi,

I am having trouble accessing the elements of an array using
reflection. This is the code I am having trouble with:

FieldInfo[] Fields = Obj.GetType().GetFields();
foreach (FieldInfo fi in Fields)
{
Object Temp = fi.GetValue(Obj);
if (Temp.GetType().IsArray)
{
// This is an array type.
MethodInfo GetLength =
Temp.GetType().GetMethod("GetLength");
Params = new Object[1];
int Length = (int)GetLength.Invoke(Temp, Params);
Object[] a = (Object[])Temp;
for (i = 0; i < Length; i++)
{
// Process array elements
}
}
}

I get a runtime error when executing the line:
Object[] a = (Object[])Temp;

The error message is:
InvalidCastException was not handled.
Specified cast is not valid.

Any ideas on what the problem is?

In the above case, it turns out the actual array is of type "Int32[]",
so if I modify the above line to become:
Int32[] a = (Int32[])Temp;

It works fine.

Any help greatfully received. Thanks.

Trevor.

Nov 17 '05 #1
3 4165
<tr************@gmail.com> wrote:
I am having trouble accessing the elements of an array using
reflection. This is the code I am having trouble with:

FieldInfo[] Fields = Obj.GetType().GetFields();
foreach (FieldInfo fi in Fields)
{
Object Temp = fi.GetValue(Obj);
if (Temp.GetType().IsArray)
{
// This is an array type.
MethodInfo GetLength =
Temp.GetType().GetMethod("GetLength");
Params = new Object[1];
int Length = (int)GetLength.Invoke(Temp, Params);
Object[] a = (Object[])Temp;
for (i = 0; i < Length; i++)
{
// Process array elements
}
}
}
For one thing, you're not putting anything into your parameter array -
shouldn't you put in the value 0?
I get a runtime error when executing the line:
Object[] a = (Object[])Temp;

The error message is:
InvalidCastException was not handled.
Specified cast is not valid.

Any ideas on what the problem is?

In the above case, it turns out the actual array is of type "Int32[]",
so if I modify the above line to become:
Int32[] a = (Int32[])Temp;

It works fine.


Well that's the problem - an array of ints isn't an array of objects.
You can't cast from object[] to int[] regardless of reflection.

I don't see why you're using reflection in the first place though - why
not just cast to Array or IList and access the members that way?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #2
<trevorelbou...@gmail.com> wrote:
I am having trouble accessing the elements of an array using
reflection. This is the code I am having trouble with:

FieldInfo[] Fields = Obj.GetType().GetFields();
foreach (FieldInfo fi in Fields)
{
Object Temp = fi.GetValue(Obj);
if (Temp.GetType().IsArray)
{
// This is an array type.
MethodInfo GetLength =
Temp.GetType().GetMethod("GetL*ength");
Params = new Object[1];
int Length = (int)GetLength.Invoke(Temp, Params);
Object[] a = (Object[])Temp;
for (i = 0; i < Length; i++)
{
// Process array elements
}
}
}


For one thing, you're not putting anything into your parameter
array - shouldn't you put in the value 0?


No. The call to "Invoke" method in the above code is calling the
"GetLength()" method for an Array type, which itself has no paramaters.
I get a runtime error when executing the line:
Object[] a = (Object[])Temp;

The error message is:
InvalidCastException was not handled.
Specified cast is not valid.
Any ideas on what the problem is?
In the above case, it turns out the actual array is of type "Int32[]",
so if I modify the above line to become:
Int32[] a = (Int32[])Temp;
It works fine.


Well that's the problem - an array of ints isn't an array
of objects. You can't cast from object[] to int[] regardless
of reflection.

I don't see why you're using reflection in the first place
though - why not just cast to Array or IList and access the
members that way?


I am using reflection because the above code is part of a Serialization
class I am writing because the .NET compact framework doesn't provide
serialization.

Yeah, I realised that I should be using Array. Thanks.

Trevor.

Nov 17 '05 #3
<tr************@gmail.com> wrote:
For one thing, you're not putting anything into your parameter
array - shouldn't you put in the value 0?


No. The call to "Invoke" method in the above code is calling the
"GetLength()" method for an Array type, which itself has no paramaters.


Yes it does - the dimension to return the length of. Look up
Array.GetLength in MSDN. If it *didn't* take any parameters, you would
have to set params to new object[0] rather than new object[1].

<snip>

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Noah Spitzer-Williams | last post by:
Hello guys, I'm itinerating through my array using pointers in this fashion: image is unsigned char image do { cout << "image byte is: " << *image << endl;
6
by: hoover_richard | last post by:
I am a newbie to C++ and I need help with a simple program I am trying to write. My program is designed to print all of the odd integers contained in an array and output the sum of the odd...
11
by: Grasshopper | last post by:
Hi, I am automating Access reports to PDF using PDF Writer 6.0. I've created a DTS package to run the reports and schedule a job to run this DTS package. If I PC Anywhere into the server on...
2
by: Jason Coyne Gaijin42 | last post by:
I have seen several people looking for a way to access the Columns collection when using the AutoGenerate = true option. Some people have gotten so far as to find the private autoGenColumnsArray...
6
by: pinetaj | last post by:
Hello, I have a question of using 'property' on accessing elements of array. There is an array member in a class. I'd like to restrict accessing the elements of the array through property. And...
5
by: ashraftm | last post by:
How do I get Array elements value from Reflection.. Here is the C# code.. I have 2 struc Public struct Address { public string city; }
11
by: ctman770 | last post by:
Hi Everyone, Is it faster to save the precise location of an html dom node into a variable in js, or to use getElementById everytime you need to access the node? I want to make my application...
9
by: Bill Grigg | last post by:
All, Can anyone supply an example or reference to an example of using reflection to determine the data types and array lengths contained in a nested stucture in C#? Actually, it is a structure...
6
by: chandramohanp | last post by:
Hi I am trying to modify class instance members using reflection. I am having problem when trying to add/remove/display elements related to List<int> member. Following is the code. class...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.