I have a C# Dictionary as follows:
Dictionary< string, myClass> dc = new Dictionary< string, myClass>();
myClass
is defined :
internal class myClass
{
public string empID;
public Decimal salary;
}
I process a file in a loop and set the myClass values then write to the Dictionary:
foreach ( DataRow row in dt.Rows)
{
myClass mc = new myClass();
mc.empID = row[0].ToString();
mc.salary = Decimal.Parse(row[1].ToString());
dc[mc.empID] = mc;
}
When I come to print the end result, the keys are correct but the dictionary values are all the same as the last row process in the above loop:
foreach ( var item in dc )
{
myClass mc = item.Value;
Console.writeLine( "Key : " + item.Key.ToString() + " Emp " + mc.empID + " sal " + mc.salary.ToString() );
}
With inputs as :
["0101","25000"]
["0202","27000"]
["0303","19999"]
The output is:
Key : 0101 Emp 0303 sal 19999
Key : 0202 Emp 0303 sal 19999
Key : 0303 Emp 0303 sal 19999
What am I doing wrong?