开发者

Object reference not set to an instance of object when using a List<T> in C# [duplicate]

This question already has answers here: What is a NullReferenceException, and how do I fix it? (27 answers) Closed 8 years ago.

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 re开发者_运维百科ference not set to an instance of an object

What am I doing wrong?


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


you have to initialize the list

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


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

public List<string> batchaddresses = new List<string>();


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

public List<string> batchaddresses = new List<string>();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜