Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Value to Array Without Specifying A Key C#

Tags:

arrays

c#

Like in PHP and some other languages, is there a way to add a value to an array without specifying the index?

int[] aWhich = {};

aWhich[] = 1;

Thanks.

like image 574
Gabriel Nahmias Avatar asked Apr 15 '26 08:04

Gabriel Nahmias


2 Answers

Not to an Array or any other type since the indexer operator must have at least one parameter (through it does not have to be an int).

You can add to the end of a List, though:

List<int> aWhich = new List<int>();

aWhich.Add(1);
like image 60
D Stanley Avatar answered Apr 17 '26 21:04

D Stanley


First of all you have to specify the maximum number of values that the array can hold:

int[] MyArray = new int[14];

Here 14 is the maximum number of values that MyArray can hold.

int value = 0;
void MyFuntion(){
       MyArray[value] = 1;
       value++;
}

In this way you can add values without specifying index number it will automatically put the index.

like image 32
Zargham Mahi Avatar answered Apr 17 '26 21:04

Zargham Mahi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!