Saturday, 17 February 2018

generics - Object reference not set to an instance of object when using a List in C#




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




public List 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.AddRange() method:



Object reference not set to an instance of an object


What am I doing wrong?


Answer



Where is batchaddresses initialized?




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



// In your constructor
batchaddresses = new List();

// Directly at declaration:
public List batchaddresses = new List();

No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...