2

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?

5
  • 3
    And how would you access it? And lets not forget that var is not what you think it is. Commented Jan 12, 2013 at 10:37
  • That is another question, that i am figuring out. But I am sure if i can get the array created, I would get sufficient information for accessing it Commented Jan 12, 2013 at 10:39
  • 2
    Thats part of the question you are asking. I think you should tell us what kind of problem are you trying to solve first. Commented Jan 12, 2013 at 10:40
  • This question is out of curiosity for the language constructs. For anything practical, this can be managed with simpler collections. Commented Jan 12, 2013 at 10:42
  • downvoter any explanation? Commented Jan 12, 2013 at 11:05

1 Answer 1

3

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.