-1

I hit a null reference exception when attempting to add a Dictionary<string,string> to a List<Dictionary<string,string>> variable. I'm unable to find the cause.

public class MyObject
{
    public List<Dictionary<string, string>> ID_Name_List { get; set; }
}

MyObject obj1 = new MyObject();

Dictionary<string, string> ID_Name_Pair = new Dictionary<string, string>();

ID_Name_Pair.Add("1", "Jane");

List<Dictionary<string, string>> ID_Name_List_2 = new List<Dictionary<string, string>>(); //For Testing

ID_Name_List_2.Add(ID_Name_Pair); //SUCCESS

obj1.ID_Name_List.Add(ID_Name_Pair); //ERROR - System.NullReferenceException: 'Object reference not set to an instance of an object.'

My obj1.ID_Name_List variable has the same List<Dictionary<string, string>> type with ID_Name_List_2

Why did my obj1.ID_Name_List hit an error while ID_Name_List_2 is successful?

Any help will be greatly appreciated

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
gymcode
  • 4,431
  • 15
  • 72
  • 128

2 Answers2

1

You have to initialize ID_Name_List.

public class MyObject
{
    public List<Dictionary<string, string>> ID_Name_List { get; set; }

    public MyObject()
    {
        ID_Name_List = new List<Dictionary<string, string>>();
    }
}
user2250152
  • 14,658
  • 4
  • 33
  • 57
1

of course you ran into a NullReferenceException. Your obj1.obj1.ID_Name_List (object) is not initialized.

try this

obj1.ID_Name_List = new List<Dictionary<string, string>();
obj1.ID_Name_List.Add(ID_Name_Pair); // will work like a charm;

alternatively,

public class MyObject
{
    public List<Dictionary<string, string>> ID_Name_List { get; set; }
    public MyObject() {
         ID_Name_List = new List<Dictionary<string, string>>();
    }
}
LongChalk
  • 783
  • 8
  • 13