Rediet T Rediet T - 3 months ago 19
C# Question

C# Set property to an object in Dictionary list - Why NullReferenceException?

This is my first question.

I have this code in my Forms App. I don't understand why i always get an NullReferenceException.

public partial class Form1 : Form
{
Dictionary<string, Product> ProductList = new Dictionary<string, Product>();

public Form1()
{
InitializeComponent();

Product product = new Product();
Position position = new Position();
product.Name = "ACAD";
position.Name = "Industry";

ProductList.Add(product.Name, product);

// NullReferenceException:
ProductList["ACAD"].PositionList.Add(position.Name, position);

// Following line works:
//listBox1.Items.Add(ProductList["ACAD"]);
}
}

class Product
{
public string Name { get; set; }
public Dictionary<string, Position> PositionList { get; set; }
}

class Position
{
public string Name { get; set; }
}


Thank you =)

Answer

Add a constructor for your product class:

class Product
{
   public string Name { get; set; }
   public Dictionary<string, Position> PositionList { get; set; }

   public Product()
   {
      PositionList = new Dictionary<string, Position>();
   }
}

And you can avoid the null reference exception from trying to add an entry to your null dictionary: ProductList["ACAD"].PositionList.Add(position.Name, position);