Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# arrays, how to create empty array?

Tags:

arrays

c#

php

I'm learning c#, with my primary language before now being php. I was wondering how (or if) you could create an empty array in c#.

In php, you can create an array, and then add any number of entries to it.

$multiples=array();
$multiples[] = 1;
$multiples[] = 2;
$multiples[] = 3;

In c#, I'm having trouble doing something similar:

int[] arraynums = new int[];
arraynums[] = 1;
arraynums[] = 2;
arraynums[] = 3;

Which gives the error "array creation must have array size or array initializer." If I don't know how many entries I want to make, how do I do this? Is there a way around this?

like image 632
James G. Avatar asked Jun 26 '26 12:06

James G.


1 Answers

If you don't know the size in advance, use a List<T> instead of an array. An array, in C#, is a fixed size, and you must specify the size when creating it.

var arrayNums = new List<int>();
arrayNums.Add(1);
arrayNums.Add(2);

Once you've added items, you can extract them by index, just like you would with an array:

int secondNumber = arrayNums[1];
like image 55
Reed Copsey Avatar answered Jun 28 '26 01:06

Reed Copsey