c#, how to play with Arrays without setting a length for it?


i am doing something with arrays and i dont want to make a limit for its length

but when i start the game i get this error:

ArgumentException: Destination array was not long enough. Check destIndex and length, and the array’s lower bounds

but the error is gone when i make the length from the editor to 5 for example.

so my question is how to not make a limit for the length and get no errors?

built-in arrays hae a fix size. If you want use built-in arrays there’s no way around specifying the length of the array. There is a resize method for built-in arrays, but it actually creates a new array with the new length and copies the elements over.

If you want to Add / remove elements frequently it’s better to use the generic List class.

The List actually holds an array internally, but it resizes the array in a more “intelligent” way. A List can be accessed like a built-in array but to add / remove elements you have special methods for that.

To use Lists you have to add this using statement at the top:

using System.Collections.Generic;

Here’s an example:

List<string> someList = new List<string>();  // creates a new list

Debug.Log(someList.Count);  // displayes "0" as the list is empty
Debug.Log(someList[0]);     // produces an error list the array would since the list is empty there is no element 0
someList.Add("Foo");        // Add some elements.
someList.Add("Hello World!");

Debug.Log(someList.Count);  // now displayes "3" as there are 3 elements in the list

someList.Remove("Bar");     // removes the first element that is "Bar"
Debug.Log(someList.Count);  // now displayes "2"
Debug.Log(someList[0]);     // prints "Foo"
Debug.Log(someList[1]);     // prints "Hello World!"
Debug.Log(someList[2]);     // error since there are only 2 elements

As i said the List uses an array internally, which got resized when it’s too small for another element. But it always reserves some space. So when adding a new element the internal array will reserve more space in the internal array so the next “Add” calls don’t need to resize the array.

You can get and set the internal capacity (the size of the internal array) by using


However the List actually handles the capacity itself so you usually don’t need to touch this at all.

If you plan to add a lot of elements to the List, you can specify the initial capacity when you create the List:

List<string> someList = new List<string>(1000);  // creates a new list with a capacity of 1000

The Debug.Log still prints “0” as the list is also empty. Only the capacity is set to 1000. That means you can call 1000 times Add before the List has to resize the internal array.

You can use ArrayLists if you want a variable sized array. Check Which Kind Of Array Or Collection Should I Use? article for more details.