I have a variant on the by ref question. I know all about calling with the ref or our parameters and how it affects variables and their values. I had this issue with a DataTable and I want to know why a datatable is different than a simple integer variable.
I have the physical answer on how to fix the problem but I want to know why it works the way it does.
If you use simple variables it does what I expected
int mVar1 = 1;
int mVar2 =1;
mVar2 = mVar1;
mVar2 = 5;
Console.WriteLine(mVar1.ToString());
Console.WriteLine(mVar2.ToString());
it displays 1,5 in the console.
BUT if you do the same thing with a DataTable it makes a reference to the first datatable instead of a new value:
DataTable mVar3 = new DataTable();
DataTable mVar4 = new DataTable();
// Create DataColumn objects of data types.
DataColumn colString = new DataColumn("StringCol");
colString.DataType = System.Type.GetType("System.String");
mVar3.Columns.Add(colString);
// Create DataColumn objects of data types.
DataColumn colString2 = new DataColumn("StringCol123");
colString2.DataType = System.Type.GetType("System.String");
mVar4.Columns.Add(colString2);
foreach (DataColumn tCol in mVar3.Columns)
{
Console.WriteLine(tCol.ColumnName);
}
foreach (DataColumn tCol in mVar4.Columns)
{
Console.WriteLine(tCol.ColumnName);
}
mVar4 = mVar3;
//change mVar4 somehow and see if mVar3 changes
foreach (DataColumn tCol in mVar4.Columns)
{
tCol.ColumnName = "Test";
}
foreach (DataColumn tCol in mVar3.Columns)
{
Console.WriteLine(tCol.ColumnName);
}
foreach (DataColumn tCol in mVar4.Columns)
{
Console.WriteLine(tCol.ColumnName);
}
The console displays: StringCol StringCol123 Test Test
by saying mVar4 = mVar3 it causes mVar4 to be a reference to mVar3.
The solution to this problem is to say
DataTable mVar4 = mVar3.Copy();
So my question is: What causes a datatable to perform differently than a simple integer field. Why does it create a reference when I use mVar4 = mVar3 instead of a different copy of the DataTable?