6

I have the following code snippet that produces a compilation error:

public List<string> batchaddresses;

public MapFiles(string [] addresses)
{
    for (int i = 0; i < addresses.Count(); i++)
    {
        batchaddresses.AddRange(Directory.GetFiles(addresses[i], "*.esy"));
    }
}

I get an error when I try to use the List<T>.AddRange() method:

Object reference not set to an instance of an object

What am I doing wrong?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
JOE SKEET
  • 7,950
  • 14
  • 48
  • 64
  • 1
    Clearly, "Object reference not set to an instance of an object" ocurrs when you try to execute your code. It is not a compilation error, its a runtime error. – Gerardo Grignoli Dec 17 '10 at 01:50

4 Answers4

12

Where is batchaddresses initialized?

Declaring the variable does not suffice. You must initialize it, like so:

// In your constructor
batchaddresses = new List<string>();

// Directly at declaration:
public List<string> batchaddresses = new List<string>();
Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
1

you have to initialize the list

List<String> batchaddresses = new List<String>();

Saif al Harthi
  • 2,948
  • 1
  • 21
  • 26
1

The batchaddresses field hasn't been initialised. You can initialise it as part of the declaration:

public List<string> batchaddresses = new List<string>();
LukeH
  • 263,068
  • 57
  • 365
  • 409
0

From your snippet, it doesn't look as though batchaddresses is initialised. Replace the line with this:

public List<string> batchaddresses = new List<string>();
Jonathon Bolster
  • 15,811
  • 3
  • 43
  • 46