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

Time:03-30

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

CodePudding user response:

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://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-6.0

  • Related