PCG
PCG

Reputation: 2307

System.NullReferenceException: When adding item to a list

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

Upvotes: 2

Views: 4357

Answers (1)

Polynomial Proton
Polynomial Proton

Reputation: 5135

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>();
        }
    }

Upvotes: 2

Related Questions