2

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;
1
  • 1
    An array is a) a reference type b) a fixed-length data-structure. You might want this sugar int[] test = { 10 }; or var test = new[] { 10 };, but otherwise, what you ask for is impossible. Perhaps you want a growable collection such as List<T>? Commented Dec 9, 2010 at 14:52

6 Answers 6

11

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.

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

1

Only that way

int[] a = {10};

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

Comments

0

Try

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

Comments

0

Use List<int> t = new List<int>() and use t.Add() method.

Comments

0

you can use this way

string[] words;
words = new List<string>() { "hello","hi" }.ToArray()

1 Comment

It would be nice to give a brief explanation of how this works / how it solves the problem, and how it's different than existing answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.