-1

I have a class which contains the object of another class. Now I want to assign the value to the member of the inner class' object using the object of parent class.

E.g.

public class DT_FLEQ
{
   private DT_FLEQHeader headerField;

   public DT_FLEQHeader Header
    {
        get
        {
            return this.headerField;
        }
        set
        {
            this.headerField = value;
        }
    }
}


DT_FLEQ FLEquipment = new DT_FLEQ();   

FLEquipment.Header.FLTYP= "Value";

It throws error: Object reference not set to an instance of an object.

Why?

Llama
  • 25,925
  • 5
  • 49
  • 68
TestinGuy
  • 11
  • 3
  • Because `headerField` is `null`. Consider this scenario: I'm having a house built with a nice garage that holds two cars. Only the house has been built so far, and there's a hole in the ground where the garage will go. I try to park my car in the garage, what happens? A big problem, right? The garage doesn't exist yet. Same situation here. Your garage is "header", your car is "Value" and your parking space within the garage is "FLTYP". – Llama Sep 22 '19 at 05:44

1 Answers1

0

As the error describes, the error occurred because the Header property was not initialized and was null. You need to initialize your headerField instance before assigning subproperties.

private DT_FLEQHeader headerField = new DT_FLEQHeader();

One way to do it would be to initialize it when declaring the variable as above. But please be aware you could do it any other place as well before the first usage. For example, within the Constructor.

public DT_FLEQ
{
headerField = new DT_FLEQHeader();
}

Or within the Setter Accessor of Header property

public DT_FLEQHeader Header
    {
        get
        {
            return this.headerField;
        }
        set
        {
            if(this.headerField == null)
            {
                 headerField = new DT_FLEQHeader();
            }     
            this.headerField = value;
        }
    }

You could also initialize it just prior to assigning the FLTYP value. For example,

FLEquipment.Header = new DT_FLEQHeader();
FLEquipment.Header.FLTYP= "Value";

The important point is, the variable headerField needs to be initialized before being assigned the value.

The alternative is creating an instance of DT_FLEQHeader and assign it to FLEquipment.Header.

var header = new DT_FLEQHeader();
header.FLTYP= "Value";
FLEquipment.Header = header;
Anu Viswan
  • 15,516
  • 2
  • 15
  • 40