Answer the question
In order to leave comments, you need to log in
Why is a NullReferenceException thrown when writing to an array?
Why is a NullReferenceException thrown when writing to an array?
using System;
public class Program
{
public static void Main()
{
XXXclass xxx = new XXXclass();
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
int i = 0;
foreach(String car in cars){
xxx.zzz[i]=car;
i++;
}
}
}
public class XXXclass
{
public string[] zzz { get; set; }
}
Answer the question
In order to leave comments, you need to log in
public class XXXclass
{
public XXXclass(){
string[] zzz = new string[4];
}
public string[] zzz { get; set; }
}
The zzz field in the XXXclass class is not created, that is, memory is not allocated just for your 4 machines.
Therefore, the i element of xxx.zzz cannot be accessed. Create a constructor like in the answer above
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question