1

I have a program as follows:

 var toppers = new List<Student>();
    var students = new List<Student>
    {
        new Student(){Name = "A", Marks = 90, Gender = 'M'},
        new Student(){Name = "B", Marks = 80, Gender = 'M'},
        new Student(){Name = "C", Marks = 70, Gender = 'M'},
        new Student(){Name = "D", Marks = 60, Gender = 'F'},
        new Student(){Name = "E", Marks = 100, Gender = 'F'},
    };

    var student = new Student();
    foreach (var stdnt in students)
    {
          if (stdnt.Marks >= 75)
          {
               student.Marks = stdnt.Marks;
               student.Name = stdnt.Name;
               toppers.Add(student);
           }
       }

       foreach (var stdnt in toppers)
       {
            Console.WriteLine(stdnt.Name + "\t" + stdnt.Marks);
       }

       Console.ReadKey();

The output I get is E 100 printed 3 times. I know how to fix it but don't know the problem with this way of implementation. Can someone please help.

Thanks

2
  • 1
    Looks like you don't yet understand how reference types work. Make sure that you do. Using C# is very surprising without this understanding. Commented Jun 14, 2014 at 11:52
  • Thanks usr. Your comment just helped me understand. I am storing the student object in toppers. not the name & marks. I got confused. Commented Jun 14, 2014 at 11:55

3 Answers 3

1

You are adding the wrong object to the toppers list. This line:

toppers.Add(student);

Should be:

toppers.Add(stdnt);

Alternatively if you want a new student object, create it in the loop with:

student = new Student();
Sign up to request clarification or add additional context in comments.

Comments

1

The problem lies in your reuse of the object student. Instead of creating a new one every time, you change the only existing one every time.

You should create a new student in every foreach like this:

foreach (var stdnt in students)
{
      if (stdnt.Marks >= 75)
      {
           var student = new Student(); // create a new student here!
           student.Marks = stdnt.Marks;
           student.Name = stdnt.Name;
           toppers.Add(student);
       }
   }

Just that easy you can do this, reusing the existing item from the list:

foreach (var stdnt in students)
{
      if (stdnt.Marks >= 75)
      {
           toppers.Add(stdnt);
       }
   }

Or even using linq:

var toppers = students.Where(x => x.Marks > 75);

1 Comment

I know this. What i want to know is the reason behind the output i'm getting?
1

In c# class objects are reference types. This means that student variable stores the reference of the actual object.

In the above code you are assigning property values of the same object, and then the reference of the same object is added three times in the list.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.