using reflection to get array of type

G

Gary Brewer

G'day,

If I have an object of type 'Type' how do I get a type of the same object as
an array of x dimensions at runtime?

For example,

Type t=typeof(string);

Type tAsArray=typeof(string[]);


Can I programmatically get tAsArray from t without having to explicity
declare the type at compile time? I would be nice if something like
t.GetAsArray(int dimensions) existed so I could do this at runtime, maybe it
does I'm just looking in the wrong place?

Regards,

Gary Brewer
 
J

Jon Skeet [C# MVP]

Gary Brewer said:
If I have an object of type 'Type' how do I get a type of the same object as
an array of x dimensions at runtime?

I don't believe there's a nice way to do this in 1.1 (there may be in
2.0). You could always create an empty array using Array.CreateInstance
and then get the type of that.
 
G

Gary Brewer

Thanks Jon,

That is actually perfect,

Type t=typeof(string);

Type tAsArray=Array.CreateInstance(t,1).GetType();

^- that is the solution to my problem. Thanks.

Gary
 
N

Nicholas Paldino [.NET/C# MVP]

Gary,

Your solution is a good one, and will work. If you want to eliminate
the overhead of the object creation, then you could just take the full type
name, and then add "[]" to it, and then get the type. However, changes in
the naming convention for the type would break this, most likely, so in that
sense, your solution is better.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Gary Brewer said:
Thanks Jon,

That is actually perfect,

Type t=typeof(string);

Type tAsArray=Array.CreateInstance(t,1).GetType();

^- that is the solution to my problem. Thanks.

Gary
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top