0

I am very new to c# and cannot find a solution to my problem.

As the title says, I would like to use a foreach() method to print all the properties of an instance.

I have this class called Item with a constructor:

class Item
    {
        public string name;
        public int stock;
        public double priceAU;

        public Item(string aName, int aStock, double aPriceAU)
        {
            name = aName;
            stock = aStock;
            priceAU = aPriceAU;
        }
    }

In my main project this code is executed:

static void Main(string[] args)
        {

            Item item1 = new Item("64GB USB", 100, 14.95 );
            Item item2 = new Item("244Hz Monitor", 50, 395.55);

            Console.ReadLine();
        }

So 2 instances of Item are created. I would like to use a foreach() method to log the name of the Instance and all of its properties. The output would look something like this:

instance | name |  stock | priceAU
item1 | 64GB USB | 100 | 14.95
item2 | 244Hz Monitor | 50 | 395.55

I can't find a solution for my problem anywhere and all of the "solutions" are really complicated and they don't even work. Very new to c# so I will be very appreciative of all answers.

gamer117
  • 13
  • 1

1 Answers1

0

this can be the solution:

static void Main(string[] args)
    {
        Item item1 = new Item("64GB USB", 100, 14.95);
        Item item2 = new Item("244Hz Monitor", 50, 395.55);

        List<Item> items = new List<Item>();
        items.Add(item1);
        items.Add(item2);

        int i = 1;

        foreach (var itm in items)
        {
            Console.WriteLine("{0}|{1}|{2}|{3}","item"+i.ToString(),itm.name,itm.stock,itm.priceAU);
            i++;
        }
    }