0

Int[] test = new int[7]

how to change test to a dynamic array?

3 Answers 3

5

There's no real notion of a stack allocated "static" array in C# (ignoring unsafe context and stackalloc). What you just wrote is a dynamic array. It's an object created at runtime on the managed heap. The size can be an expression or variable. For instance:

int[] a = new int[int.Parse(Console.ReadLine())];

If by dynamic array, you mean an array you can resize easily (like vector in C++), you should use List<T>:

List<int> a = new List<int>();
a.Add(10);
Sign up to request clarification or add additional context in comments.

Comments

0

Maybe you want to change it to a List<int>? If that were the case:

int[] test = new int[7];

List<int> testList = new List(test);

Comments

0

Actually, this can be achieved by using the ToList() extension method (you will need to import the System.Linq namespace). Here is an example:

int[] numbers = { 2, 3, 4, 5 };
IList<int> numbersDynamic = numbers.ToList();

That would give you a list class that you can manipulate as needed.

2 Comments

any difference between this and SnOrfus?
Same result, different approach.

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.