Question

It seams simple enough but I cannot append values into my master dictionary. I think this is because the dict has an object elements instead of just a simple type and I don't have the syntax correct on "masterDict.Add" method. I know some of my object values are set, some are empty string, and some are null, but I don't think this is the source of the issue - the object does exist. It crashes on "newMsg.Value".

My error:

System.NullReferenceException was unhandled
HResult=-2147467261
Message=Object reference not set to an instance of an object.

    Example Code:

    public class msg
    {
        public string msgId { get; set; }
        public string msgType { get; set; }
        public string lastName { get; set; }
        public string firstName { get; set; }
        public string dateOfBirth { get; set; }
        public string sex { get; set; }
        public string pAddress { get; set; }
        public string pPhone { get; set; }
        public IEnumerable<string> prodCode { get; set; }
        public string dateOfServiceText { get; set; }
     } 
    public static Dictionary<String, msg> masterDict { get; set; }

    public static Dictionary<String, msg> tmpDict = new Dictionary<String, msg>()
    {
        { "1111", new msg { msgId = "1111", msgType = "DFT", firstName="Sachin" }},
        { "1112", new msg { msgId = "1112", msgType = "DFT", firstName="Dina" }},
        { "1113", new msg { msgId = "1113", msgType = "DFT", firstName="Andy" }}
    };

    public static void mergeDict()
    {

        //now insert your new values into the master
        foreach (var newMsg in tmpDict)
            if (newMsg.Value != null)
                masterDict.Add(newMsg.Key, newMsg.Value);
    }

    static void Main(string[] args)
    {
        mergeDict();
    }
Was it helpful?

Solution

You never initialized your masterDict:

public static Dictionary<String, msg> masterDict { get; set; }

This doesn't set it to anything. It will be equal to null until you set it:

masterDict = new Dictionary<String, msg>();

You probably want to do it in your class constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top