Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 849
JOE SKEET Avatar asked Dec 17 '10 01:12

JOE SKEET


People also ask

What is object reference not set to an instance of an object C?

The message "object reference not set to an instance of an object" means that you are referring to an object the does not exist or was deleted or cleaned up. It's usually better to avoid a NullReferenceException than to handle it after it occurs.

How can we avoid object reference not set to an instance of an object in C#?

The best way to avoid the "NullReferenceException: Object reference not set to an instance of an object” error is to check the values of all variables while coding. You can also use a simple if-else statement to check for null values, such as if (numbers!= null) to avoid this exception.

How do I fix object reference is not set to an instance of an object?

To fix "Object reference not set to an instance of an object," you should try running Microsoft Visual Studio as an administrator. You can also try resetting the user data associated with your account or updating Microsoft Visual Studio to the latest version.


1 Answers

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>();
like image 96
Etienne de Martel Avatar answered Oct 31 '22 04:10

Etienne de Martel