Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding object to a list, changes all other list objects

Tags:

c#

list

I’m trying to add animals to my animal list, but the values of the last added animal will be all the animals in the list.

List<Animal> animals = new List<Animal>();
public bool AddAnimal(Animal animal)
        {
            animals.Add(animal); 
            return true;
        } 

Animal animal = new Animal();
private void btnAddAnimal_Click(object sender, RoutedEventArgs e)
        {
            animal.AnimalSize = Size.large;
            animal.Carnivore = true;
            AddAnimal(animal);
        }

This is the list: Size Carnivore - Large True

private void btnAddAnimal_Click(object sender, RoutedEventArgs e)
        {
            animal.AnimalSize = Size.large;
            animal.Carnivore = false;
            AddAnimal(animal);
        }

This is what happens with my animals list after I add an Herbivore:

  • Size Carnivore
    • Large false
    • Large false
like image 899
Salomé Avatar asked Dec 31 '25 15:12

Salomé


1 Answers

Well, you don't actually add a new Animal, you're merely modifying the one you have. If you want to add a new animal, you have to create a new object:

private void btnAddAnimal_Click(object sender, RoutedEventArgs e)
{
  Animal animal = new Animal();
  animal.AnimalSize = Size.large;
  animal.Carnivore = true;
  AddAnimal(animal);
}
like image 138
Lennart Avatar answered Jan 03 '26 05:01

Lennart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!