I've started learning C# and I have been following a few "mini projects" I found on the net and some I made up my self to help me understand the basics. This mini project requires me to create two classes that are named "item" and "inventory". The idea is that the item class is used to create items and the other inventory class is used to store the items and print them all. Here's the code so far:
class Program
{
static void Main(string[] args)
{
inventory my_inventory = new inventory();
item cake = new item("Cake", 2.99, 001);
item carrot = new item("Carrot", 0.59, 002);
my_inventory.add_item(cake);
my_inventory.add_item(carrot);
my_inventory.print_inv();
Console.ReadLine();
}
}
class item
{
string name;
double price;
int id;
public item (string Name, double Price, int ID)
{
this.name = Name;
this.price = Price;
this.id = ID;
}
public item()
{
this.name = "unknown";
this.price = 0.00;
this.id = 000;
}
public override string ToString()
{
return "Name: " + name + " Price: " + price + " ID Number: " + id;
}
}
class inventory
{
object[] inv_list = new object[10];
int tracker = 0;
public void add_item(object obj)
{
inv_list[tracker] = obj;
tracker++;
}
public void print_inv()
{
foreach ( object obj in inv_list) { Console.WriteLine(obj.ToString()); }
}
}
The error I keep running into is the "NullReferenceException" inside the print_inv()
method and from what I have read it means that the object I'm trying to use on the print_inv() method is null? I'm not sure what this means in my code.