Bassem
Bassem

Reputation: 103

Datarow object, why is this code working?

after assign a row values of datatabe to a new data row object , any changes in this object affects on the data table , Why ?

have a look at this code.

  DataRow dr = mydataset.Tables["NewTable"].Rows[0];
  dr["Name"] = "hello";

Now if you try to debug your application you will find that the original data table ["NewTable"] has the new value hello instead of the old value Although we didn't return back the above data row to data table (we didn't save it )

I Just need a clarification and also need to know & understand what actually happen when i create an Object of a data row .

Upvotes: 0

Views: 32

Answers (1)

NightOwl888
NightOwl888

Reputation: 56869

Both DataTable and DataRow are reference data types. This means that when you assign a variable to its reference in code, it simply holds a pointer back to the same memory location.

DataRow dr1 = mydataset.Tables["NewTable"].Rows[0];
DataRow dr2 = mydataset.Tables["NewTable"].Rows[0];
DataRow dr3 = dr1;
DataTable dt = mydataset.Tables["NewTable"];
DataRow dr4 = dt.Rows[0];

In the above example, dr1, dr2, dr3, and dr4 all point to the same memory location. Therefore if you edit dr4, the changes will appear on dr1, dr2, and dr3.

See Value Types and Reference Types for more information.

Upvotes: 1

Related Questions