You are creating a single instance of Test
Test test = new Test(); // This is your instance
IList<Test> myList = new List<Test>();
foreach (DataRow dataRow in dataTable.Rows)
{
// Here you change the values of the existing instance each time you loop
test.PatientID = Convert.ToInt64(dataRow.ItemArray[0]);
test.LastName = dataRow.ItemArray[1].ToString();
test.FirstName = dataRow.ItemArray[2].ToString();
myList.Add(test); // but you are still just adding the same reference to the list multiple times
}
And then since you are never creating a new Test
instance, you are adding the same reference to the list multiple times. This means that you are essentially just storing the same object over and over: if you make any changes to one item in the list it will immediately be visible in all others because they are essentially the same object
The solution is to move the instantiation of test inside the loop
IList<Test> myList = new List<Test>();
foreach (DataRow dataRow in dataTable.Rows)
{
Test test = new Test(); // Each loop iteration will now create a new instance of Test
test.PatientID = Convert.ToInt64(dataRow.ItemArray[0]);
test.LastName = dataRow.ItemArray[1].ToString();
test.FirstName = dataRow.ItemArray[2].ToString();
myList.Add(test);
}
If you need to understand this better, look at reference and value types in .NET and passing by reference/value
Value and Ref types in .NET:
http://msdn.microsoft.com/en-us/library/t63sy5hs.aspx
Some info on pointers on Wikipedia
http://en.wikipedia.org/wiki/Pointer_(computer_programming)