C# Object reference not set to an instance of an object. Instantiating Class within a List?

。_饼干妹妹 提交于 2019-12-21 04:25:21

问题


public class OrderItem
{
    public string ProductName { get; private set; }
    public decimal LatestPrice { get; private set; }
    public int Quantity { get; private set; }
    public decimal TotalOrder { get {return LatestPrice * Quantity;}}

    public OrderItem(string name, decimal price, int quantity)
    {

    }

    public OrderItem(string name, decimal price) : this(name, price, 1)
    {

    }
}

Above is the class, just for some background.

public void AddProduct(string name, decimal price, int quantity)
{
    lstOrderitem.Add(new OrderItem(name, price, quantity));           
}

On the code inside the AddProduct method is where I am getting the error stated in the title.

I'm just trying to instantiate the class and add it to a collection to be displayed in a listbox on my form program.

The "AddProduct" will be called on a button click event

Error = NullReferenceException - Object reference not set to an instance of an object.

I was wondering if anybody knew why this was happening since I thought that since I am making a NEW instance of the class while adding it to the list that it would have something to reference too. Thank you if anybody knows what the problem is.

Edit

    public List<OrderItem> lstOrderitem{ get; private set; }
    public int NumberOfProducts { get; private set; }
    public decimal BasketTotal { get; private set; }

    public ShoppingBasket()
    {
        //List<OrderItem> lstOrderitem = new List<OrderItem>();
    }

    public void AddProduct(string name, decimal price, int quantity)
    {
        lstOrderitem.Add(new OrderItem(name, price, quantity));


    }

回答1:


You should initialize lstOrderitem property in the constructor, like this:

EDIT

public MyClass() {
    lstOrderitem = new List<OrderItem>();
}

P.S. Microsoft suggests starting the names of your properties in capital letters, to avoid confusion with member variables, which should be named starting with a lowercase letter.




回答2:


It looks like you didn't initialize your reference lstOrderitem. Debug your code if your references value is null, you need to initialize lstOrderitem before using it.




回答3:


It looks like you didn't initialize your reference lstOrderitem. Debug your code if your reference value is null, you need to initialize lstOrderitem before using it.

public MyClass() {
    lstOrderitem = new List<OrderItem>();
}


来源:https://stackoverflow.com/questions/8701846/c-sharp-object-reference-not-set-to-an-instance-of-an-object-instantiating-clas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!