Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Reflection: how do I loop through an object that is an array type?

I've got a method that returns an array, the type of which I have stored in a Type object further up. The code I have for this is thus:

Type StoryType = Type.GetType("my.ns.Story");
Type StoryTypeArray = Type.GetType("my.ns.Story[]");

object stories = SomeMethodInfo.Invoke(BigFatObject,some_params);

In this example, I know stories is of type StoryTypeArray, and what I really want to do is something like:

foreach (Story instance in stories) { ... }

However, I can't figure out how to turn the object stories into something I can loop through and pull data out of.

Any ideas?

like image 878
growse Avatar asked Jun 07 '11 17:06

growse


People also ask

How do you loop through an object in an array?

To iterate through an array of objects in JavaScript, you can use the forEach() method aong with the for...in loop. The outer forEach() loop is used to iterate through the objects array. We then use the for...in loop to iterate through the properties of an individual object. ✌️ Like this article?

Can you loop through object in C#?

In c#, the Foreach loop is useful to loop through each item in an array or collection object to execute the block of statements repeatedly. Generally, in c# Foreach loop will work with the collection objects such as an array, list, etc., to execute the block of statements for each element in the array or collection.


1 Answers

It's not clear from your question if the Story type is actually known to you at compile time. If it is, the solution is trivial; just cast stores to Story[] and iterate over it as usual:

foreach(Story instance in (Story[])stories) { ... }

This also means that StoryType can be written as typeof(Story) and StoryTypeArray can be written as typeof(StoryTypeArray[]) instead of using the less-safe Type.GetType that you're using.

If the type is not actually known to you at compile time, then you won't be able to write foreach(Story instance..., since that won't be a valid type. If you just want to iterate over the array, then you can do this:

foreach(object item in (Array)stories) { ... }
like image 97
Adam Robinson Avatar answered Oct 24 '22 05:10

Adam Robinson