Dynamic arrays

  • Thread starter Thread starter Roger Webb
  • Start date Start date
R

Roger Webb

I'm sure this has been asked before ... however, I didnt find it ..so I'm
asking it anyway.

I've got a function that has to return an int[]. The function has to build
it, however, I dont know the number of items in order to create it. Whats
the easiest/fastest way to create one of an unknown size?

- Roger
 
Roger Webb said:
I'm sure this has been asked before ... however, I didnt find it ..so I'm
asking it anyway.

I've got a function that has to return an int[]. The function has to
build
it, however, I dont know the number of items in order to create it.
Whats
the easiest/fastest way to create one of an unknown size?

Either determine the size before hand(if thats possible without being to
computationally expensive) or use ArrayList\List<T>(if you are using the 2.0
framework), add items to it, and call ToArray() to create an array out of
the members.
 
When you say that you "don't know the number of items", I assume that
you mean at compile time, when you're writing the program. The easiest
way to do this at run time is using an ArrayList:

ArrayList list;

.... list.Add(myInt); ... (fill up the ArrayList)
return (int[])list.ToArray(typeof(int));
 
Back
Top