Home > Software engineering >  How can I call this subroutine to fill my array?
How can I call this subroutine to fill my array?

Time:10-28

So I am making a vending machine code as a project, and I need to use this call this routine to fill my array:

static void Main(string[] args)
        {
             Product[] machine = new Product[9]; 
             //This is where i want to call the LoadItems routine to fill the machine array//
        }

        public struct Product
        {
            public string name;
            public double price;
        }

        public static void LoadItems(Product[] machine)
        {
            machine[0].name = "Cheese";
            machine[0].price = 2.00;

            machine[1].name = "Salami";
            machine[1].price = 1.50;

            machine[2].name = "Kitkat";
            machine[2].price = 1.00;

            machine[3].name = "Fanta";
            machine[3].price = 1.80;

            machine[4].name = "Sharp hamburger";
            machine[4].price = 4.30;

            machine[5].name = "Coconut water";
            machine[5].price = 0.80;

            machine[6].name = "Crackers";
            machine[6].price = 2.00;

            machine[7].name = "Orange juice";
            machine[7].price = 0.75;

            machine[8].name = "Water";
            machine[8].price = 0.60;
        }

    }

I have tried using LoadItems();, and LoadItems(Product[] machine);

Apologies as I am new to C#

CodePudding user response:

Call it like this:

LoadItems(machine);

But better practice looks like this:

public struct Product
{
    public string name;
    public decimal price; // use decimal rather than double for money
}

// return a value, rather than mutate a passed argument
public static Product[] LoadItems()
{
    // array/collection initializer syntax
    return new Product[] {
       //object initializer syntax
       new Product() {name = "Cheese", price = 2.0M},
       new Product() {name = "Salami", price = 1.5M},
       new Product() {name = "Kitkat", price = 1.0M},
       new Product() {name = "Fanta",  price = 1.8M},
       new Product() {name = "Sharp hamburger", price = 4.3M},
       new Product() {name = "Coconut water", price = 0.8M},
       new Product() {name = "Crackers", price = 2.0M},
       new Product() {name = "Orange juice", price = 0.75M},
       new Product() {name = "Water", price = 0.6M}
    };
}

static void Main(string[] args)
{
   Product[] machine = LoadItems(); 
}

I could also comment on the advisability of a mutable struct (C# developers nearly always use a class or the newer record) as well as whether arrays are the most suitable collection here, but I think there's already enough to digest for the moment.

  • Related