6

What is wrong here?

string[] keysDictionary = new string[]{};
keysDictionary [0] = "test";

I get

System.IndexOutOfRangeException Array index is out of range.

9
  • Because that is an array with 0 of length, you should do new string[length] Commented Sep 12, 2014 at 10:38
  • Do I need the length? Or can I create an empty array and add later values to it (I don't know how many values before)? Commented Sep 12, 2014 at 10:39
  • 1
    @testing In that case you need List<string> not array Commented Sep 12, 2014 at 10:40
  • You should look into using List<T>. It's an array-like structure that allows the addition of more elements. Commented Sep 12, 2014 at 10:40
  • 1
    @testing, even though C# is a high level language it still has some very basic constructs, like fixed arrays which you are trying to use. Only use arrays (ie ´type[]´ syntax like int[]) when you create a fixed collection you are going to be iterating over many times. In my opinion, for all other cases the performance gain is not worth the hassle of keeping track of the array size manually. Commented Sep 12, 2014 at 12:44

5 Answers 5

11

You can't add anything to a 0 length array. You are essentially trying to set the value of the first element of an array with no elements. Use something like a list instead if you want to do this, arrays cannot be resized.

var keysDictionary = new List<string>();
keysDictionary.Add("test");
Sign up to request clarification or add additional context in comments.

2 Comments

How can this answer have upvotes when it won't even compile due to the typo in line 2?
Because it is just a typo. Answer is already clear without compiling.
6

By stating {} you are defining this as an empty array.

Thus you should either define the size as:

string[] keysDictionary = new string[1];
keysDictionary [0] = "test";

Or

Initialize like this:

string[] keysDictionary = new string[]{"test"};

Comments

2

new string[]{} creates zero-length array

Comments

1

You need to specify the size of the array.

e.g.

string[] keysDictionary = new string[1];
keysDictionary [0] = "test";

Comments

0

If you want an Array that dynamically changes size when you add values use a List instead.

3 Comments

ArrayList is a bit .net 1.1, more commonly you would use List<T>
Sorry I'm too used to Java I just assumed C# had a similar feature
using Arraylist is not recommended from the moment of generics implementation in c#

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.