Elia Giaccardi Old
Elia Giaccardi Old

Reputation: 262

Is there any way to not have to specify an array size before modifying its elements?

Let's say I want to write a value in a int[], but I don't yet know what will be the length of that array.

Currently, I just run whatever algorithm I'm using once to get the length of the array, then I instanciate the array and finally run the same algorithm modifying the elements of the array.

Here's a code example:

for (int i = 0; i < input.length; i++)
{
    if (i == condition)
    {
        length++;
    }
}

array = new int[length];

for (int i = 0; i < input.length; i++)
{
    if (i == condition)
    {
        array[i] = whatever;
    }
}

Upvotes: 1

Views: 76

Answers (1)

Just use lists

List<string> list = new List<string>();

When adding elements just do:

list.Add("Hello, world!");

You do not need to specify length for a list and you can add as many elements as you like

https://www.c-sharpcorner.com/article/c-sharp-list/

https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-6.0

Upvotes: 5

Related Questions