Animimo
Animimo

Reputation: 53

Previous Values Get Overwritten in my List in C#

My previous list value gets overwritten by the new ones I input into my ReadLine().

These is one of my classes.

public class Car
{
    public string ID { get; set; }

    public string capacityKg { get; set; }

    public string reachKm { get; set; }

    public string registrationNumber { get; set; }
}

I declare my List and Class here:

        List<Car> allCars = new List<Car>();

        Car vehicle = new Car();

Here is my problem: Everytime I run this code inside my switch statement / do while loop the previous value gets overwritten. For example I input "Car123" the first time I run it and then it outputs Car123 but the second time I add a new value to my list like "car234" it replaces "Car123" with "car234"


    vehicle = new Car();

    Write("ID: ");
    vehicle.ID = ReadLine();

    Write("Capacity (kg): ");
    vehicle.capacityKg = ReadLine();

    Write("Reach (km): ");
    vehicle.reachKm = ReadLine();

    Write("Registration number: ");
    vehicle.registrationNumber = ReadLine();

    Clear();

    WriteLine($ "ID: {vehicle.ID}");
    WriteLine($ "Capacity (kg): {vehicle.capacityKg}");
    WriteLine($ "Reach (km): {vehicle.reachKm}");
    WriteLine($ "Registration number: {vehicle.registrationNumber}");

    WriteLine(" ");
    WriteLine("Is this correct? (Y)es (N)o");

    ConsoleKeyInfo yesNo = ReadKey(true);

    // I want to run a code here that checks if the registration number already exists
    if (yesNo.Key == ConsoleKey.Y) {
      allCars.Add(vehicle);

      Clear();

      WriteLine("Delivery unit registered");

      Thread.Sleep(2000);

      Clear();

      break;
    }
    else if (yesNo.Key == ConsoleKey.N) {
      Clear();
    }
    else {
      Clear();

      WriteLine("Invalid key pressed.");

      Thread.Sleep(2000);

      Clear();
    }

Upvotes: 0

Views: 319

Answers (1)

Caius Jard
Caius Jard

Reputation: 74605

The problem is because you declare your car outside the loop:

vehicle = new Car();

Then inside the loop you change the car details and add it to the list:

do{

  vehicle.Name = Console.ReadLine();
  list.Add(vehicle);

} while ...

Because you never make a new object, all you're doing is adding the same car repeatedly to the list, and altering its name, which means after 5 iterations of the loop you will have 1 object in memory (that has had its name changed 5 times), and 6 references pointing to this same object (one is vehicle and the other 5 references are list[0], list[1] ...)

Upvotes: 1

Related Questions