-1

I am creating a webapi for a shop type service. I am running into a NullReferenceException when using a class I have written which doesnt make sense. Here is my api code:

    [HttpGet]
    public HttpStatusCode Get()
    {
        Item item1 = new Item("Chips", 1, false);
        Console.WriteLine(item1.ToString());
        
        Items collection = new Items("a");
        collection.addItem(item1);

        Items collections = new Items("a");
        collections.addItem(item1);
        Console.WriteLine(collections.getSize());
        return HttpStatusCode.OK;
    }

My Item code:

public class Item
{
    public Item(string Name, double Price, bool GlutenFree)
    {
        this.itemID = Guid.NewGuid();
        this.name = Name;
        this.price = Price;
        this.glutenFree = GlutenFree;
    }

    public Guid itemID;
    public string name;
    public double price;
    public bool glutenFree;

And lastly the items class:

    public Items(string a){
        this.name = a;
    }

    public string name;
    public ArrayList itemCollection;

    public int getSize()
    {
       

The idea is an individual item will be part of a larger item collection - so for example a coke can will be part of a drinks collection.

The problem I am having is when I run this code it runs into an error at the adding an item to the items arraylist. I tried instantiating a local arraylist in the Get() method and this does work, however it does not give me the flexibility I need and is not suitable. I am not sure why this error is happening, I have run a if (collection is null) check and it does not return null for it. I am not sure why this error is happening and would appreciate advice

EDIT: Realised I am not doing new ArrayList() in my items class which meant a array list was never created. Fixed now.

Yohan
  • 359
  • 1
  • 3
  • 12
  • 2
    At which line specifically does the exception occur? Please [edit] the question and provide [all the exception details](https://idownvotedbecau.se/noexceptiondetails/) including the stack trace. – 41686d6564 stands w. Palestine Nov 16 '20 at 02:08

1 Answers1

-1

The following line create your class. So it is an object and is not null.

Items collection = new Items("a");

I do not see in there where you are instantiating your list. In C# you have to instantiate it before you can add any items to it or it will throw a null reference.

Do a null check on collection.itemCollection. It is likely null.

Kupokev
  • 169
  • 8
  • Curious why the downvote when what I pointed out was exactly what the OP says their problem was? – Kupokev Nov 16 '20 at 05:01