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());
       }
    }
8
  • 1
    You either mean array, list or arraylist. Which do you mean? If you mean arraylist, then that is a bad decision. Commented Aug 7, 2021 at 7: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 Commented Aug 7, 2021 at 7:36
  • 2
    Don't use an arraylist. Use a List<Product>. Call Add on it. Commented Aug 7, 2021 at 7:38
  • 1
    And name it AddProduct(). Standard C# convention. Commented Aug 7, 2021 at 7:42
  • 1
    why using arraylist is not a good choice? Commented Aug 7, 2021 at 7:49

1 Answer 1

-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

Sign up to request clarification or add additional context in comments.

1 Comment

But in this way I have to make the objects inside the class.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.