Creating typed arrays using reflection

  • Thread starter Thread starter Ranier Dunno
  • Start date Start date
R

Ranier Dunno

Hi,

I'd like to create typed arrays during runtime, sort of
like this:

Array vals = Array.CreateInstance(objType, noElements);

The problem is that objType will not be a "base" type
like Double or Int32, but rather an array type, like
Double[] or Int32[]. Is there any way of creating, say,
an array of doubles from the double[] system type?
 
Ranier Dunno said:
I'd like to create typed arrays during runtime, sort of
like this:

Array vals = Array.CreateInstance(objType, noElements);

The problem is that objType will not be a "base" type
like Double or Int32, but rather an array type, like
Double[] or Int32[]. Is there any way of creating, say,
an array of doubles from the double[] system type?

Yup - you just need to get the element type, which you can do with
Type.GetElementType. In other words:

Array vals = Array.CreateInstance (objType.GetElementType(),
noElements);
 
-----Original Message-----
Ranier Dunno said:
I'd like to create typed arrays during runtime, sort of
like this:

Array vals = Array.CreateInstance(objType, noElements);

The problem is that objType will not be a "base" type
like Double or Int32, but rather an array type, like
Double[] or Int32[]. Is there any way of creating, say,
an array of doubles from the double[] system type?

Yup - you just need to get the element type, which you can do with
Type.GetElementType. In other words:

Array vals = Array.CreateInstance (objType.GetElementType (),
noElements);

Ah, so there was a method - thanks :-)
 
Back
Top