2

Let's say I have a completely empty array

int num = 1;
int[] arr = new int[0];

I just want to add the variable num to the arrat in the next possible position, like the .Add function for lists in C#. How would I do this without having to specify where I put it, only what to put. I do not want to use any Lists, basically just how the .Add function works for lists, but for arrays

I tried just using the .Add function but that didn't work. This was my full code:

public class Program
{
    public static int[] MultiplyByLength(int[] arr)
    {
        int[] finallist = new int[0];
        int curnum = 0;
        foreach(int item in arr)
        {
            curnum = item * arr.Length;
            finallist.Add(curnum);
        }
        return(finallist);
    }
}

But, clearly, it didn't work. how would I make the finallist.Add(curnum) line to work?

BORBZABY
  • 29
  • 2
  • 1
    You wouldn't, because you can't add to an array... its length is fixed on creation. You'd have to create an array of the right size to start with. (Or potentially create a new array on each iteration, but that would be horribly inefficient.) – Jon Skeet Aug 21 '23 at 16:28
  • finallist = finallist.Concat(arr).ToArray(); This will add arr items to finallist array. See this link for more info: https://code-maze.com/add-values-to-csharp-array/ – SoftwareDveloper Aug 21 '23 at 16:31
  • 1
    `I do not want to use any Lists` why? Is there an actual reason for this or just an assumption? `List` stores items in an internal array anyway. When a new item is added and the array is full, a new array with double the size is allocated and the existing data copied over. – Panagiotis Kanavos Aug 21 '23 at 16:38
  • @SoftwareDveloper that's the slow way to do what `List.Add` also does. `Concat` returns an `IEnumerable`. `ToArray()` internally adds items to a buffer with reallocation once it's empty. At least with `List(capacity)` you can specify the expected size and avoid reallocations. – Panagiotis Kanavos Aug 21 '23 at 16:45
  • This (my answer) is likely pertinent: https://stackoverflow.com/questions/51511209/best-way-to-push-into-c-sharp-array/51531294#51531294. Note that lists keep track of their _capacity_ (how many elements have currently been allocated - though that is changeable) and how many elements have actually been added. That way, when you `Add` to a list, it knows where to do the insert (if the capacity runs out, it resizes itself internally). Arrays have no concept of "next possible position" – Flydog57 Aug 21 '23 at 16:46
  • This misunderstands what an array really is at a basic level. Contrary to what certain other platforms will do, from a pure computer science standpoint a real array is a **FIXED** collection of contiguous memory blocks accessible by index. When other platforms give you an "array" and allow you do things like append, that's not really an array anymore. Rather, it's an array-like collection. The .Net platform, by contrast, gives you **real** arrays. It also happens to give you a nice selection of array-like collections, if that's what you want. But when you ask for an array, that's what you get. – Joel Coehoorn Aug 21 '23 at 17:05

1 Answers1

1

how would I make the finallist.Add(curnum) line to work?

You can't, array's in C# have fixed size and it can't be changed after creation:

The number of dimensions and the length of each dimension are established when the array instance is created. These values can't be changed during the lifetime of the instance.

So the Add function does not make sense in case of arrays.

But you actually do not need it, just create an array of needed size and use for loop:

static int[] MultiplyByLength(int[] arr)
{
    int[] finallist = new int[arr.Length];
    for (var index = 0; index < arr.Length; index++)
    {
        var item = arr[index];
        var curnum = item * arr.Length;
        finallist[index] = curnum;
    }

    return finallist;
}

P.S.

There is Array.Resize but it actually does the following:

This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one. array must be a one-dimensional array.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • 1
    (For the OP) the next evolution would be to look at LINQ and IEnumerables. The whole function can be a single line `return arr.Select(x => x * arr.Length).ToArray();`. – gunr2171 Aug 21 '23 at 16:34
  • @gunr2171: although the for loop is more efficient. You know the final size of the array, so you can create it with the correct size. Your solution will always resize the array during enumeration. You could maybe use: `var list = new List(arr.Length); list.AddRange(arr.Select(x => x * arr.Length)); return list.ToArray();` – Tim Schmelter Aug 21 '23 at 17:08