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

余生颓废 提交于 2019-12-10 13:45:15

问题


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?


回答1:


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



回答2:


you have to initialize the list

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




回答3:


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

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



回答4:


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

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


来源:https://stackoverflow.com/questions/4466878/object-reference-not-set-to-an-instance-of-object-when-using-a-listt-in-c-shar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!