I found a weird behaviour (a bug?) in .NET Framework and .NET when it comes to DataColumn renaming. Here's how to reproduce it.
- Take a DataColumn in a DataTable
- Rename it so that you only change its casing
- Rename it again to something different
- Now the column will be available both under the old and under the new name
- If you rename it back to the old name, you'll get a DuplicateNameException
The problem seems related to the DataColumnCollection's internal dictionary not getting updated when a column gets renamed to only change its casing.
DataTable table = new DataTable();
table.Columns.Add("foo", typeof(string));
// The DataTable contains a single column named "foo"
// The dictionary _columnFromName contains a single entry having its key equal to "foo"
table.Columns["foo"].ColumnName = "FOO";
// The DataTable now contains a single column named "FOO"
// The dictionary _columnFromName did not get updated, so the entry key STILL equal to "foo"
table.Columns["FOO"].ColumnName = "bar";
// The DataTable now contains a single column named "bar"
// Here the DataColumnCollection registers the new columnname "bar", but fails the unregistration of the column name "FOO", because the dictionary does not contain a key equal to "FOO".
// So, the dictionary _columnFromName now contains TWO entries having their keys equal to "foo" and "bar"
// In fact, the column is still available under the old name ...
Console.WriteLine(table.Columns["foo"]);
// ... and of course it is also available under the new name "bar"
Console.WriteLine(table.Columns["bar"]);
// Now, this will throw a DuplicateNameException, because the old dicionary key is still present
table.Columns["bar"].ColumnName = "foo";
Here's a .NET Fiddle targeting .NET Framework 4.7.2. You can change it to .NET 7 and you will still encounter this problem. https://dotnetfiddle.net/vhoV6X
Has anyone else encountered this behaviour? Is it intended? Is it known to Microsoft?