Tilak
Tilak

Reputation: 30728

How to create variable dimension array at runtime?

I want to create variable length multi-dimension array at runtime.

Input -> Array that has length of each dimension. Number of dimensions = length of input array.
Output -> variable dimension array.

Example:
Input -> var lengths = new [] {3,4,5}
Expected output -> var arr = new string[3,4,5]

How to do that without and with reflection?

Upvotes: 2

Views: 1906

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273711

There is this method in the System.Array class :

public static Array CreateInstance(
Type elementType,
int[] lengths    
)

See this question for a discussion of GetLength() and GetUpperBound()

But do note that because you don't know the dimensions at compile time you cannot use the familiar a[i,j,k] syntax. All access would look like int[] indices = ...; object x = a.GetValue(indices);

Upvotes: 3

Related Questions