I have a parent class called Snack with subclasses Drink and Sweets. I want to store my Snacks in a "VendingMachine" Class where there is a list for each of the Products. However, I don't want to write the same method for each type of Snack. How would you write this as a generic method ?
// DRINKS LIST
List<Drink> drinks = new List<Drink>();
public List<Drink> Drinks { get => drinks; set => drinks = value; }
private void FillWithProducts <Product> (params Product[] products) where Product : Snack
{
Type typeParameter = typeof(Product);
Type drink = typeof(Drink);
foreach (Product p in products)
{
if (typeParameter.Equals(drink))
{
Drinks.Add(p);
}
}
}
I think maybe there's a different way of doing this. With your base
SnackBasebase class and derivedDrinkandSweetclasses, you can fill aVendingMachineclass with snacks then get the drink and sweet lists from the vending machine. The code below illustrates this:Base Class
Derived classes
VendingMachine.cs
Program.cs