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;
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With