L
L
Light7772020-06-12 13:35:13
C++ / C#
Light777, 2020-06-12 13:35:13

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; }
  }


Run-time exception (line 14): Object reference not set to an instance of an object.

Stack Trace:

[System.NullReferenceException: Object reference not set to an instance of an object.]
at Program.Main() :line 14

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Korotenko, 2020-06-12
@Light777

public class XXXclass
{
public XXXclass(){
string[] zzz = new string[4];
}
public string[] zzz { get; set; }
}

S
Sergei Chamkin, 2020-06-12
@Sergei1337

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 question

Ask a Question

731 491 924 answers to any question