1

I am having an issue when trying to add an item to a list. I see many questions but I still don't get it in my case. This is my definition :

public class DBStatus
    {
        [DataMember]
        public DBOperation Type { get; set; }
        [DataMember]
        public List<DBMessageType> Message { get; set; }
        [DataMember]
        public List<string> InnerException { get; set; }
    }

I declared this class and trying to add an item.

private void button19_Click_1(object sender, EventArgs e)
    {
        DBStatus dbstst = new DBStatus();
        dbstst.Message.Add(DBMessageType.INVALID_OR_EXPIRED_FUNCTION_REQUEST);
        dbstst.InnerException.Add("testing code");

        int k = 0;
    }

I get System.NullReferenceException when adding the items.

Error message: "System.NullReferenceException: 'Object reference not set to an instance of an object.'"

I know my last two list items are null post declaration, why can not I add ?

Any help is appreciated.

thanks, PG

1

1 Answer 1

2

A List is null by default and you need to initialize the list before adding elements into it

Option 1 :

private void button19_Click_1(object sender, EventArgs e)
    {
        DBStatus dbstst = new DBStatus();

        dbstst.Message = new List<DBMessageType>();
        dbstst.Message.Add(DBMessageType.INVALID_OR_EXPIRED_FUNCTION_REQUEST);

        dbstst.InnerException = new List<string>();
        dbstst.InnerException.Add("testing code");

        int k = 0;
    }

Option 2 : You can also do this via class constructor :

public class DBStatus
    {
        [DataMember]
        public DBOperation Type { get; set; }
        [DataMember]
        public List<DBMessageType> Message { get; set; }
        [DataMember]
        public List<string> InnerException { get; set; }

        public DBStatus(){ //initialize here
          Message = new List<DBMessageType>();
          InnerException = new List<string>();
        }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. Option 2 saved a lot of time as I only have to change constructor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.