-2

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?

New contributor
Oleg is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
2
  • 1
    data_Zkl_Koms[N].AddData(zn, time, rez); - You never initialized data_Zkl_Koms[N] to anything, so it's null. The error is telling you that you can't call a method on null. In your main method you are first initializing the array element and then using it. The same is true of any array element. Initialize data_Zkl_Koms[N] to a new Data_Zkl_Kom() and then you can use that new Data_Zkl_Kom instance. Commented Oct 8 at 20:21
  • 1
    Nitpicking: this is not an "array of classes", but an "array of objects of type Data_Zkl_Kom". Commented Oct 9 at 15:01

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.