Home > Net >  When I append something to my array it doesn't add anything to the list
When I append something to my array it doesn't add anything to the list

Time:07-28

basically I'm trying to append something to an array, but for some reason in wont even work.

(gObject is a thing with a name and a value)

public gObject[] OBJECTS = {};
public void RegisterObjectToRender(gObject reg)
{
    OBJECTS.Append<gObject>(reg);
    for (int ri = 0; ri < OBJECTS.Length; ri  )
    {
       Console.WriteLine(OBJECTS[ri].Name);
    }
}

I hope everyone who is reading this is having a good day btw

CodePudding user response:

Arrays are fixed size, always. If you want a list: use a list, i.e. use List<Your type> instead of an array. A list has an Add method.

I'm guessing the Append method here is a local extension method that only exists in your code (that isn't a normal API). I'm also guessing that it calls Array.Resize internally, but: that creates a new and different array - it doesn't change the existing array. So if you use that, you'd need to swap the underlying reference afterwards, too - to the new array reference. However, don't do that: Array.Resize is incredibly inefficient, as it allocates a new array every append (contrast List<T> which keeps an oversized backing array, and tracks the count separately, only increasing the underlying array occasionally).

CodePudding user response:

Append returns a new IEnumerable. It does not add to the OBJECTS, but essentially returns a new list. You have to capture the result of Append and use that: var extendedList = OBJECTS.Append(reg).

A better way is to use a list and use Add instead of Append. It is faster and cleaner.

  • Related