Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does datatable.Clear, clears the other datatable as well?

Tags:

c#

.net

DataTable dttemp = new DataTable();
dttemp=orderedTable;
dttemp.Rows.Clear();

for some reason the orderedTable is being cleared as well! does anyone know why this is happening?

like image 962
JOE SKEET Avatar asked Jan 27 '26 02:01

JOE SKEET


2 Answers

By the time you've executed this line:

dttemp = orderedTable;

there's only actually one DataTable which is relevant. The DataTable you created in the first line of code is eligible for garbage collection - nothing's taking any notice of it. The line quoted here doesn't make a copy of the object - it makes a copy of the reference, so that dttemp and orderedTable refer to the same DataTable.

DataTable is a reference type. It's absolutely vital that you understand how reference types work in C# - otherwise the whole language will have baffling results for you. I have an article which you may find useful along those lines.

To put your code into context, imagine that a DataTable is actually a house. You give your home address to two different people. One goes and paints the house red... and then the other visits the house. Obviously he'll find it's red.

The important thing is that you didn't give each person "your house" - you just gave them a way of getting to your house. That's how reference types work in C#.

The value of dttemp isn't a DataTable - it's a reference to a DataTable. Changes made to that object via any other variables will still be seen via dttemp.

like image 174
Jon Skeet Avatar answered Jan 28 '26 15:01

Jon Skeet


You have two variables (dttemp and orderedTable) which, at the time when you call Clear(), point at the same object. Thus a change to the object pointed to by dttemp is also a change to the object pointed to by orderedTable.

The table you create with new DataTable() is simply discarded onto the heap (waiting to be garbage-collected) when you assign dttemp=orderedTable;

like image 28
Marc Gravell Avatar answered Jan 28 '26 15:01

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!