Max Max - 24 days ago 7
C# Question

Adding to list with foreach loop

I am currently trying to add objects(students). I am creating in a foreach loop to an object list made up of students, each list object ends up referencing to the same location and therefore the information on each list object is the same as the last student object created when the loop ends. The only information I have been able to find for adding an object to a list using a foreach loop states to create a new instance of the object which I thought I was doing with the Student stud = new Student line.

I have also tried using the default constructor and using properties instead of arguments, then adding the student to the list however I receive the same result.

Any help in adding objects to an object list with a foreach loop would be greatly appreciated.

foreach loop:

foreach (DataRow datrow in dt.Rows)
{
Student stud = new Student(
datrow["ID"].ToString(),
datrow["fName"].ToString(),
datrow["lName"].ToString(),
datrow["GPA"].ToString(),
datrow["Graduate"].ToString()
);
studentList.Add(stud);
}


My Student Constructor:

public Student(
string studentID,
string fName,
string lName,
string studentGPA,
string graduate)
{
iD = studentID;
firstName = fName;
lastName = lName;
gPA = studentGPA;
grad = graduate;
}


statement used to fill dt

OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter dc = new OleDbDataAdapter(cmd);
dc.Fill(ds, "ID");
dt = ds.Tables["ID"];
const char DELIM = ',';
foreach (DataRow datrow in dt.Rows)


"this" information that each object refers to and is re-written for every new object



Result


Answer

Your private variables are most likely static. This would explain why the variables already have a value in the constructor (which they wouldn't for normal instance variables). The static values are being returned by your properties (which explains how they have values already as well). Change your variables to instance (not static)