2

I'm learning C# and I have created a code to add random numbers to a List using a for loop.

class Program
{
    static void Main(string[] args)
    {
        Random numberGen = new Random();
        List<int> randomNum = new List<int>();
        for (int i = 0; i < 10; i++)
        {
            randomNum.Add(numberGen.Next(1, 100));
        }
        for (int i = 0; i < randomNum.Count; i++)
        {
            Console.WriteLine(randomNum[i]);
        }       
        Console.ReadKey();       
    }      
}

I want to know if there is a way to add random numbers to an array with a similar method?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 1
    No it is not. Arrays have a fixed length which cannot be changed. You'll need to copy the Array with `n` more slots and fill those n slots. [Which is what a List does](https://stackoverflow.com/questions/16387286/is-listt-really-an-undercover-array-in-c) – MindSwipe Jun 19 '20 at 10:44

3 Answers3

5

The size of an array is fixed at the time of creation, so you can't add to an array; you can, however: create a new array that is bigger, copy the old data, and then append the new value(s) - Array.Resize does the first two steps - but: this is pretty expensive, which is why you usually use a List<T> or similar for this scenario. A List<T> maintains an oversized array in the background, so that it only has to resize and copy the underlying array occasionally (essentially, it doubles the size every time it gets full, so you get something approximating O(Log2(N)) overhead due to growth).

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

You could just assign to the relevant index directly, but note you'll have to initialize the array to the required size (as opposed to a List that can grow dynamically):

int[] randomNum = new int[10];
for (int i = 0; i < randomNum.Length; i++)
{
    randomNum[i] = numberGen.Next(1, 100);
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

Use a List<T>, thats is the scenario it was precisely designed for. Once you've finished adding elements to it, if you need an array then simply call ToArray():

var myList = new List<int>();
//add random number of random numbers
var myArray = myList.ToArray();
InBetween
  • 32,319
  • 3
  • 50
  • 90