0

I have a class with a string and dictionary properties:

public class Student
{
    public int StudentId { get; set; }
    public Dictionary<string, decimal> LevelGpa { get; set; }
}

Which I am trying to populate into a list of Students:

List<Student> students = new List<Student>()
{
    {new Student{StudentId = 1, LevelGpa = {{"Freshmen",3.1m}}}},
    {new Student{StudentId = 1, LevelGpa = {{"Sophomore",3.2m}}}},
    ...
};

But it is throwing a NullReferenceException at run time -

Object reference not set to an instance of an object.

What am I missing here?

user793468
  • 4,328
  • 22
  • 74
  • 120

1 Answers1

1

You should create an instance of LevelGpa inside each instance of Student object:

List<Student> students = new List<Student>()
{
    {new Student() {
                    StudentId = 1, 
                    LevelGpa = new Dictionary<string, decimal>() {"Freshmen",3.1m} 
                   }
    },

    ...
};
Sparrow
  • 2,278
  • 1
  • 24
  • 27