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?
It’s not clear from your question if the
Storytype is actually known to you at compile time. If it is, the solution is trivial; just caststorestoStory[]and iterate over it as usual:This also means that
StoryTypecan be written astypeof(Story)andStoryTypeArraycan be written astypeof(StoryTypeArray[])instead of using the less-safeType.GetTypethat 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: