Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding values to the array without initialization the length

When I can add values to the array , Exception occurs. In C# , can i set the values without initializing the array length.

int[] test;
test[0] = 10;
like image 313
Hset Hset Aung Avatar asked Nov 22 '25 09:11

Hset Hset Aung


2 Answers

No, if you want a data structure that dynamically grows as you Add items, you will need to use something like List<T>. Arrays are fixed in size.

When you have

int[] test;

you haven't instantiated an array, you've merely declared that test is a variable of type int[]. You need to also instantiate a new array via

int[] test = new int[size];

As long as size is positive then you can safely say

int[0] = 10;

In fact, you can say

int[index] = 10

as long as 0 <= index < size.

Additionally, you can also declare, instantiate and initialize a new array in one statement via

int[] test = new int[] { 1, 2, 3, 4 };

Note that here you do not have to specify the size.

like image 135
jason Avatar answered Nov 24 '25 22:11

jason


You can't do that with an array, per se, but you can use a List.

        List<int> test = new List<int>();
        test.Add(10);
like image 30
PhilDearmore Avatar answered Nov 24 '25 21:11

PhilDearmore



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!