kodkod
kodkod

Reputation: 1576

Why did Clear() clear both DataTables?

In my winform program (in vb.net) I wrote:

Dim dt As New DataTable
'Get data from DB into dt
'...

Dim dttemp As New DataTable
dttemp = dt
dt.Clear()
'...

But when I run the program, Clear() cleared both dt and dttemp! Why? Aren't dt and dttemp supposed to be two distinct instances of DataTable?

(I finally found a solution - dttemp = dt.Copy() instead of dttemp = dt. But I still can't see why Copy() was necessary in this case. Sorry if it's a basic question - I'm a beginner programmer.)

Upvotes: 1

Views: 905

Answers (4)

SWeko
SWeko

Reputation: 30902

Whenever you do variable = New Something you are creating an instance of that class, and setting up a reference that points to that particular instance.

So, in your code dt and dttemp are just references to a DataTable object.

So what your code does is:

  1. Create a new DataTable object, and set the dt reference to point to it
  2. Create another DataTable object, and set the dttemp reference to point to it
  3. Set the dttemp reference to point to whatever dt is referencing (in this case the first data table). This effectively orphans the second data table, and makes it eligible for garbage collection.

So, since both dt and dttemp are referencing the same object, whatever is done via the one, will be visible via the second.
When you are doing dt.Copy() you are creating another instance of the DataTable class, copying the values from the first to the second datatable, and returning the second. That way you have two separate instances, that you can manage as you wish.

Upvotes: 0

Andrey
Andrey

Reputation: 60075

You should do:

Dim dt As New DataTable
'Get data from DB into dt
'...

Dim dttemp As New DataTable
dttemp = dt.Copty()
dt.Clear()
'...

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1501626

It's because DataTable is a reference type.

The values of dttemp and dt are just references to the same object.

If I write my address down on a piece of paper and give it to two people, then one of them burgles me (clears my house/DataTable) then if the second person visits me they'll find the house empty. That's what's happening here.

I have an article (C#-based, but the same applies) about reference types and value types which you may find useful.

Upvotes: 3

SLaks
SLaks

Reputation: 887657

When you write dttemp = dt, you're changing dttemp to refer to the same DataTable instance as dt.

It doesn't create a separate copy of the instance.

Value types (structs) behave the way you're expecting, but reference types (classes) do not.

Upvotes: 4

Related Questions