-1

I have a problem with arrays of strings.

public string[] Begin;    
....
for (int i = 0; i < Int32.Parse(Areas); i++)
{
    Begin[i] = text.Substring(j, 4);
}

It gives an System.NullReferenceException error.

But it works fine without an array:

public string Begin;    
....
for (int i = 0; i < Int32.Parse(Areas); i++)
{
    Begin = text.Substring(j, 4);
}

I just can't understand what is the difference and how can I fix it?

  • Has Begin been initialized with any strings? If it has that part of the code isn't represented in what you have above. – Bradford Dillon Jan 28 '15 at 14:58
  • Welcome to Stack Overflow. `NullReferenceException` is a common situation for beginner programmers. The link provided should help you understand the problem. Then use the debugger to find what/where/when you have a variable that is `null`. And please read [FAQ], [ask] and [help] as a start.. – Soner Gönül Jan 28 '15 at 14:59
  • _"what is the difference"_ - `Begin[i] =` versus `Begin =`. See duplicate. – CodeCaster Jan 28 '15 at 14:59
  • Thank you. Tried to find themes like my, but without result. – Viktor Karaulov Jan 28 '15 at 15:09

1 Answers1

-1

Because you never initialized Begin array so is null. You need to instantiate it before being able to assign something to it.

You could initialize your array like this

Begin = new string[Int32.Parse(Areas)];

Difference between string[] and string is quite big. First is an array of strings that may hold one or more string instances. Second is a single string.

Claudio Redi
  • 67,454
  • 15
  • 130
  • 155