jpummill
jpummill

Reputation: 3

c# add updated instance of class to list without duplicates

I'm trying to use an instance of a class to add data to a list (of the same class). If I only enter one record it works fine but if I update the instance and add a second (or third, etc...) all rows in the list contain the last update to my temporary instance.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _13._5_Functions
{
    class Dog
    {
        public string Name;
        public int Age;
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<Dog> Dogs = new List<Dog>();
            Dog myDog = new Dog();

            myDog.Name = "Ralph";
            myDog.Age = 14;

            Dogs.Add(myDog);

            myDog.Name = "Spot";
            myDog.Age = 8;

            Dogs.Add(myDog);

            foreach (Dog d in Dogs)
            {
                Console.WriteLine("Name: " + d.Name + "    Age: " + d.Age);
            }

            Console.Read();
        }
    }
}

Result:

Name: Spot Age: 8

Name: Spot Age: 8

Upvotes: 0

Views: 77

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

It is because Classes are reference types and your object is reffering to same memory location and when you are changing it's state, it is changing value at that memory location.

You have to assign new memory by creating new instance every time before adding new item in the list, otherwise it will update same memory location

List<Dog> Dogs = new List<Dog>(); 

Dog myDog = new Dog(); 

myDog.Name = "Ralph"; 
myDog.Age = 14; 

Dogs.Add(myDog);

myDog = new Dog(); // note this line

myDog.Name = "Spot"; 
myDog.Age = 8; 

Dogs.Add(myDog);

Read this article about Value Types and Reference Types in C#

Upvotes: 4

Related Questions