C# List Assigned Values

ASPDEV
ASPDEV used Ask the Experts™
on
Hello Experts,

I have an issue with C# List, when I add values it showing the duplicates data.

using System;
using System.Collections.Generic;

public class Program
{
	public static void Main()
	{
		Student std = new Student();
		List<Student> studentList = new List<Student>();
		
		std.ID = 1;
		std.Name = "John";
		studentList.Add(std);
		
		
		std.ID = 2;
		std.Name = "Doe";
		studentList.Add(std);	
		
		
		Console.WriteLine(studentList.Count);//count
		
		Console.WriteLine(studentList[0].ID); //ID
		Console.WriteLine(studentList[0].Name); //Name
	}
}

public class Student
{ 
	public int ID { get; set; }
	public string Name { get; set; }
}

Open in new window


Output:
2
2
Doe

The count was correct, but I was expecting below output and the list shows duplicates:

2 -- >Count
1 --> ID
John -- > Name

Please help, what I was doing incorrect.

Thanks,
ASPDEV
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Senior Developer
Commented:
You must add a new object. Cause the list stores only the reference to it. So reusing the object variable as you do is wrong. E.g.

namespace ConsoleCS
{
    using System;
    using System.Collections.Generic;

    public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public override string ToString()
        {
            return $"{ID}, {Name};";
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            List<Student> studentList = new List<Student>();

            Student std1 = new Student();
            std1.ID = 1;
            std1.Name = "John";
            studentList.Add(std1);

            Student std2 = new Student();
            std2.ID = 2;
            std2.Name = "Doe";
            studentList.Add(std2);

            Console.WriteLine(studentList.Count);
            Console.WriteLine(studentList[0]);
            Console.WriteLine(studentList[1]);

            Console.WriteLine("\nDone.");
            Console.ReadLine();
        }
    }
}

Open in new window

Author

Commented:
Thanks.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial