0

I want to store Product objects in a array list. Below is the definition of the product class.

    class Product
    {
       public string name;
       public int iD;
       public int price;

       public void addProduct()
       {   
          Console.WriteLine("Enter Name : ");
          name = Console.ReadLine();
          Console.WriteLine("Enter ID : ");
          iD = int.Parse(Console.ReadLine());
          Console.WriteLine("Enter Price : ");
          price = int.Parse(Console.ReadLine());
       }
    }
Kraego
  • 2,978
  • 2
  • 22
  • 34
MubMalik
  • 17
  • 2
  • 1
    You either mean array, list or arraylist. Which do you mean? _If you mean arraylist, then that is a bad decision._ – mjwills Aug 07 '21 at 07:31
  • yes I want to store this data in ArrayList and whenever I take input from user I want to store data in the next index nd so on – MubMalik Aug 07 '21 at 07:36
  • 2
    Don't use an arraylist. Use a `List`. Call `Add` on it. – mjwills Aug 07 '21 at 07:38
  • 1
    And name it AddProduct(). Standard C# convention. – H H Aug 07 '21 at 07:42
  • 1
    why using arraylist is not a good choice? – MubMalik Aug 07 '21 at 07:49
  • https://stackoverflow.com/questions/5063156/why-isnt-arraylist-marked-obsolete – Steve Aug 07 '21 at 07:53
  • @MubMalik "*why using arraylist is not a good choice?*" => Because [deprecated and obsolete](https://learn.microsoft.com/dotnet/api/system.collections.arraylist?#remarks) in addition to be untyped and useless to use: *We don't recommend that you use the ArrayList class for new development. Instead, we recommend that you use the generic Listclass. The ArrayList class is designed to hold heterogeneous collections of objects. However, it does not always offer the best performance.*" –  Aug 07 '21 at 08:15
  • Does this answer your question? [ArrayList vs List<> in C#](https://stackoverflow.com/questions/2309694/arraylist-vs-list-in-c-sharp) and [Why isn't ArrayList marked "Obsolete"?](https://stackoverflow.com/questions/5063156/why-isnt-arraylist-marked-obsolete) and [What is the difference between an Array, ArrayList and a List?](https://stackoverflow.com/questions/32020000/what-is-the-difference-between-an-array-arraylist-and-a-list/32020072) and [C# objects in arrayLists](https://stackoverflow.com/questions/3367524/c-sharp-objects-in-arraylists) –  Aug 07 '21 at 08:15

1 Answers1

-1

Based on your requirement I think the below code will work for you.

        ArrayList arrList = new ArrayList();
        Product prod1 = new Product();
        prod1.addProduct();
        arrList.Add(prod1);
        Product prod2 = new Product();
        prod2.addProduct();
        arrList.Add(prod2)

I would suggest using List as it is generic. You can find more about ArrayList Vs List here. link