adding values to the array without initialization the length

22,775

Solution 1

Only that way

int[] a = {10};

But the length of the array will be 1 after that.

Solution 2

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.

Solution 3

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);
Share:
22,775
Hset Hset Aung
Author by

Hset Hset Aung

Updated on July 09, 2022

Comments

  • Hset Hset Aung
    Hset Hset Aung almost 2 years

    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;