I would like to know how I can get an object upon it's creation. I have two classes, a class called Product, and another class called Inventory, which is a static class. Here's the definition of the product class:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
}
Here's the definition of the Inventory class:
public static class Inventory
{
public static List<Product> Products { get; set; }
}
What I would like to do it's the following, when an object of type Product it's created, this object should be added to the Inventory.Products
list, so later I can query for inventory information.
I would like to be able to do something like this inside the Product class:
public class Product
{
public Product()
{
Inventory.Products.Add(this);
}
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
}
However if I use the constructor to do this I will get an NullReferenceException
, because Products
is not yet initialized. Where is the best place to initialize the static Products
list?