-4

I'm trying to create an ArrayList with cars I've created using a constructor class and then afterwards use a foreach loops to then print the model name of each cars.

I've created the car objects as following

Car car1 = new Car("Audi e-tron", "Black", 2021);
Car car2 = new Car("Audi RS7", "Black", 2021);
Car car3 = new Car("Audi A5", "Black", 2021);

I created the ArrayList and attempted to begin adding the car objects to the ArrayList

ArrayList carList = new ArrayList();
carList.Add(car1);
carList.Add(car2);
carList.Add(car3);

I tested to see if the code was working properly up to this point and checked if the ArrayList has populated

Console.WriteLine("car list: {0}", carList[0]);

but that returns

ArrayListPractice.MainClass+Car

How can I add objects from the constructor to the ArrayList and return a parameter of the object? Thank you!

Abbe Azale
  • 11
  • 2
  • 3
    We have 2021, why you stil use an `ArrayList`?? Use a `List` – Tim Schmelter Feb 12 '21 at 21:02
  • 1
    You are doing it correctly, it is just that calling ToString() on an object that does not have ToString() overriden will just give you the class name. So, override ToString in `Car` to output what you want to see. Also, why are you using ArrayList? That is long dead. – Crowcoder Feb 12 '21 at 21:02
  • 1
    hi there. I would actually use the strongly typed List<> instead of ArrayList. So declare the list like this: var carList = new List(); Also, if you want to print the name you either need to override the ToString() function in the Car class or write something like: Console.WriteLine( carList[0].Name ); – Ocean Airdrop Feb 12 '21 at 21:03
  • You might want to look at my answer to this question: https://stackoverflow.com/questions/65365412/c-how-can-i-add-an-object-into-array/65365550#65365550. It doesn't directly address your issues, but it uses cars (which is why it sounded familiar) and touches on some aspects of your problems – Flydog57 Feb 12 '21 at 22:24

2 Answers2

0

What exactly are you trying to print in the code block below?

Console.WriteLine("car list: {0}", carList[0]);

If you want to print the string property you passed into the constructor of the first element ("Audi e-tron"), for example, try this:

Console.WriteLine("car list: {0}", carList[0].Name); // 'Name' should be the field name you're looking for
work89
  • 75
  • 8
  • As @Crowcoder pointed out above, added a `ToString` override to the `Car` class will provide a way to see the information about each car that you include in that method. – Flydog57 Feb 12 '21 at 21:08
0

You should override the Car object, ToString() method and there is no need to other considerations, it will be automatically done

Amir
  • 1,214
  • 7
  • 10