Click here to Skip to main content
15,916,215 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to assign data to a child class attribute with in a parent class in c#. I am getting object reference not set to instance of object issue.

What I have tried:

My class is as below:

    public class Header
    {
        public string ReferenceNo { get; set; }
    }

    public class Detail
    {
        public string ROLEID { get; set; }
      
    }

    public class GetRoleDetailsResponse
    {
        public Header Header { get; set; }
        public List<Detail> Details { get; set; }
    }

    public class Root
    {
        public GetRoleDetailsResponse GetRoleDetailsResponse { get; set; }
    }

While trying to assign as below, getting null exception:

GetRoleDetailsResponse obj = new GetRoleDetailsResponse();
           obj.objHeader.ReferenceNo = "54654646";

           obj.Details[0].ROLEID="abc";
Posted
Updated 26-Apr-21 4:18am
v2

1 solution

Well yes, of course you are - and thirty seconds with the debugger would have shown you why! Once it compiled, that is (there is no property objHeader in the GetRoleDetailsResponse class)
You create a new instance of the container class GetRoleDetailsResponse but you don't populate either of the fields it contains.
Try adding defaults to your properties:
C#
public class GetRoleDetailsResponse
    {
        public Header Header { get; set; } = new Header();
        public List<Detail> Details { get; set; } = new List<Detail>();
    }

You'll still get an error on the other line because the list is empty so element 0 doesn't exist, but ... I'm sure you can fix that!
 
Share this answer
 
Comments
ranio 26-Apr-21 12:23pm    
first issue is gone. but in the second one i am getting out of index range issue on assigning
I added as below:
List<detail> Details = new List<detail>
{
new Detail {ROLEID = "12345"}

};

//obj.Details.Add("123");
//obj.Details[0].ROLEID = "abc";

objGetRoleDetailsResponse.Details[0].ROLEID = Details[0].ROLEID.ToString(); //at this point getting i am getting out of index range issue on assigning
i am returning this class object
OriginalGriff 26-Apr-21 13:36pm    
And what do you expect that to do?

Think about it logically ...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900