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?
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.
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.
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.
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With