-1

I want to add every item of the store to a list and calculate the selling price of the item using another class (which I haven't created yet) but I'm struggling to create the list so it adds the instance of the class "Item". Using .Net Core 3.1. This is my code:

PS: The class is in a new tab in VisualStudio

using System;
using System.Collections.Generic;
using System.Linq;

namespace StockPriceCalculator
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            var list = new List<Tuple<string, double>>();
            Item nails = new Item("Nails", 5.5);

            list.Add(nails);
        }
    }
    public class Item
    {
        public Item(string name, double price)
        {
            this.name = name;
            this.price = price;
        }
        public string name { get; set; }
        public double price { get; set; }
    }
}
  • If your `class Item` is meant to be immutable then you should change the properties to `{ get; }` and not `{ get; set; }`. – Dai Jul 08 '22 at 17:08
  • The `price` would be better as `decimal` since it is currency. – Ňɏssa Pøngjǣrdenlarp Jul 08 '22 at 17:48
  • @ŇɏssaPøngjǣrdenlarp Yep: the `double` and `float` (aka `Single`) types must never be used to represent currency/money values: https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency – Dai Jul 08 '22 at 18:50

2 Answers2

0

Maybe i didnt understand you but why you dont create a list of "item"?

Like that:

         public static void Main(string[] args)
            {
                var list = new List<Item>();
                Item nails = new Item("Nails", 5.5);

                list.Add(nails);
            }
        }
        public class Item
        {
            public Item(string name, double price)
            {
                this.name = name;
                this.price = price;
            }
            public string name { get; set; }
            public double price { get; set; }
        }
NGDeveloper
  • 160
  • 10
0

If you want a list of Item objects then create a List<Item>, not a List<Tuple<string, double>>. If you create the latter then you can only add Tuple<string, double> objects to it.

user18387401
  • 2,514
  • 1
  • 3
  • 8
  • I want it to have 2 variables - name and price – KristiyanArnaudov Jul 08 '22 at 17:09
  • @KristiyanArnaudov, so what? You are creating an `Item` object with those two variables, not a `Tuple`. You need a list that can store the type of object you have. What type of object do you have? An `Item`, right? So create a `List`. – user18387401 Jul 08 '22 at 17:11