I tried to create a class with three fields and then use it in another class as an array.
class Program
{
public class Data_Zkl_Kom
{
float ZN { get; set; }
int Time { get; set; }
int Rez { get; set; }
public void AddData(float zn, int time, int rez)
{
ZN = zn;
Time = time;
Rez = rez;
}
public float GetZN() { return ZN; }
public int GetTime() { return Time; }
public int GetRez() { return Rez; }
}
public class Data_Zkl
{
Data_Zkl_Kom[] data_Zkl_Koms { get; set; }
public Data_Zkl(int k)
{
data_Zkl_Koms = new Data_Zkl_Kom[k];
}
public void AddData(int N, float zn, int time, int rez)
{
data_Zkl_Koms[N].AddData(zn, time, rez);
}
public int GetLen()
{
return data_Zkl_Koms.Length;
}
}
static void Main(string[] args)
{
Data_Zkl[] massZn = new Data_Zkl[5];
massZn[0] = new Data_Zkl(10);
massZn[0].AddData(0,1,1,1);
}
}
When created, it enters the constructor of the Data_Zkl class, but why don't I see three variables? In the debugger I expected to see an array of Data_Zkl_Kom elements, but instead I see null. enter image description here enter image description here
After executing the command massZn[0].AddData(0,1,1,1); an exception is thrown System.NullReferenceException: "Object reference not set to an instance of an object." What am I doing wrong or maybe I forgot something?
data_Zkl_Koms[N].AddData(zn, time, rez);
- You never initializeddata_Zkl_Koms[N]
to anything, so it'snull
. The error is telling you that you can't call a method onnull
. In yourmain
method you are first initializing the array element and then using it. The same is true of any array element. Initializedata_Zkl_Koms[N]
to anew Data_Zkl_Kom()
and then you can use that newData_Zkl_Kom
instance.