using reflection to get array of type

  • Thread starter Thread starter Gary Brewer
  • Start date Start date
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
 
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.
 
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
 
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
 
Back
Top