-1

I'm new to C# coming from C++

I'm currently building a cigarette inventory management system, and I'm creating a separate List to store different brands.

When I add a Cigarette object which carries a title and a MaxInventory to the list, and I go to print it out my output is the project.className

How can I have the program print to console the actual data stored within the list. I need to see a report of the brand and amount of cigarettes currently in the list.

        Cigarette marbLight = new Cigarette("Light", 6);
        Cigarette marbRed = new Cigarette("Red", 6);

        List<Cigarette> marlboro = new List<Cigarette>()
        {
           marbLight, marbRed
        };

        marlboro.ForEach(Console.WriteLine);

The output:

        InventoryManagement.Cigarette

        InventoryManagement.Cigarette

Desired output would be the contents of marbLight and marbRed

Thanks in advance!

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
FranticCode
  • 3
  • 1
  • 1
  • 5

2 Answers2

0

Console.WriteLine will call ToString on what is passed into it. You can override it in your Cigarette class.

public override string ToString()
{
    return // whatever you want here
}
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

As the other person said, you would have to override the ToString method in your Cigarette class. An alternative syntax for it is

// and your other variables you want to show
public override string ToString() => String.Format("Cigarette contents: {0}", contents);
dtasev
  • 540
  • 6
  • 12