-1

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 =)

Rediet T
  • 1
  • 1

1 Answers1

1

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);

Jakotheshadows
  • 1,383
  • 1
  • 12
  • 23