Share via


object.List.add() :Object reference not set to an instance of an object.

Question

Thursday, September 12, 2013 11:59 AM

Hello there,

I have a class that has a list as one of poreties I try to set a list of other class in that but I get the "Object reference not set to an instance of an object." error ! I cannot figure it out what is wrong here :

the logic of a code is there is conversations that holds lots messages, we look for new messages then we find what conversation that message is belong to. assing the message to conversationand assign conversation to ConversationList 

Code : 

List<ChatBoxConversationItem> ConversationList = new List<ChatBoxConversationItem>();
List<ChatBoxMessagesItem> Newmessages = ChatBoxMessages.GetIncommingMessages(toID, false);

            foreach (ChatBoxMessagesItem msg in Newmessages)
            {
                var found = ConversationList.FirstOrDefault(c => c.ID == msg.ConversationID);
                if (found != null)
                {
                    found.chatMessages.Add(msg);
                }
                else
                {
                    ChatBoxConversationItem conv = ChatBoxConversation.GetChatBoxConversationItemByID(msg.ConversationID);
                    conv.chatMessages.Add(msg); // << I get the Error Here !
                    ConversationList.Add(conv);
                }
            }

public class ChatBoxConversationItem
    {
        public List<ChatBoxMessagesItem> chatMessages { get; set; }
        public Int32 ID { get; set; }
        public string Title { get; set; }
        public Int32 FromUserID { get; set; }
        public Int32 ToUserID { get; set; }
        public DateTime StartDateTime { get; set; }   
    }

Thanks in advance  

All replies (2)

Thursday, September 12, 2013 12:06 PM âś…Answered

You'll need to ensure that the collection isn't null and is properly instantiated prior to adding an object to it.

You'll want to either handle this within the actual Constructor or method that creates your ChatBoxConversationItem class or prior to adding a value to it, check if it exists and if not simply create it : 

//Create your conversation (you might want to ensure that you are populating your List within your GetChatBoxConversationItem method)
ChatBoxConversationItem conv = ChatBoxConversation.GetChatBoxConversationItemByID(msg.ConversationID);

//Check if your Messages collection exists
if(conv.chatMessages == null)
{
      //It's null - create it
      conv.chatMessages = new List<ChatBoxMessagesItem>();
}

//Add your message to the now existing collection
conv.chatMessages.Add(msg);
ConversationList.Add(conv);

Thursday, September 12, 2013 12:56 PM

Awosome Rion !

Now it works like a charm!