locked
Object reference not set to an instance of an object while assigning array to list RRS feed

  • Question

  • User1897897189 posted

    Dears,

    How to assign array to list?

    Following is what i have, and its returning Object reference not set to an instance of an object

    public class aResponse
    {
    public List<aBasic> aRequest { get; set; }

    }


    public class aBasic
    {
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    }


    aResponse response = new aResponse();
    aBasic StudentInfo = new aBasic();
    aBasic.StudentID = "1";
    aBasic.StudentName = "a";
    response.aRequest .Add(StudentInfo);

    Thanks

    Thursday, March 28, 2019 4:01 AM

Answers

  • User1724605321 posted

    Hi nicklibee ,

    You should initialize before assign values :

    aResponse response = new aResponse();
    aBasic StudentInfo = new aBasic();
    StudentInfo.StudentID = 1;
    StudentInfo.StudentName = "a";
    response.aRequest = new List<aBasic>();
    response.aRequest.Add(StudentInfo);

    Best Regards,

    Nan Yu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, March 28, 2019 5:25 AM

All replies

  • User1724605321 posted

    Hi nicklibee ,

    You should initialize before assign values :

    aResponse response = new aResponse();
    aBasic StudentInfo = new aBasic();
    StudentInfo.StudentID = 1;
    StudentInfo.StudentName = "a";
    response.aRequest = new List<aBasic>();
    response.aRequest.Add(StudentInfo);

    Best Regards,

    Nan Yu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, March 28, 2019 5:25 AM
  • User1897897189 posted

    thank you so much

    Thursday, March 28, 2019 6:07 AM