开发者

How to identify whether the objects are just referenced or just copied? .net Memory Management

I'm confused to find whether an object is either copied or the reference of the object is held while equating it to s开发者_Go百科ome other objects.

Examples

int i =5;
int j = i;

Reference or copy of data?

DataSet ds = dsOtherDataSet.Copy();

Reference or copy of data?

DataView dvTemp = dsTestDataSet.Copy().DefaultView;

What happens here?

Regards

NLV


int i = 5;
int j = i;

Copy of data as int is a value type and is stored on the stack.

DataSet ds = dsOtherDataSet.Copy();

According to the documentation the Copy method copies both the structure and data of the DataSet. So ds will have the same structure as the original but if there are reference values stored inside both will point to the same memory location.

DataView dvTemp = dsTestDataSet.Copy().DefaultView;

Only the reference is copied as DataView is a reference type.


if type is struct then copy is always done by value. if class then by reference.

What is done inside methods like Copy, Clone etc. is not strictly defined and is up to the one who implements them.

In case of DataSet.Copy msdn tells us that deep copy is done ("Copies both the structure and data for this DataSet."), meaning that it completely recreates dataset. Still, Copy method returns reference to new dataset.


In the first case the int's aren't objects they are value types. So for "int j = i" another int is created and then the value from i is copied into it. If you use Copy then it probably creates another copy of the object using deep copy. But you should find out wheter the copy is a deep-copy or just a shallow copy. If you would use DataSet ds = dsOtherDataSet, or Object obj = someOtherObject then only their adress is passed, so it is by reference only.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜