Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shallow copy in c#

Tags:

c#

I understand the definition of shallow copy

Shallow copying is creating a new object and then copying the non-static fields of the current object to the new object. If a field is a value type --> a bit-by-bit copy of the field is performed; for a reference type --> the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.

but why static fields are not copied?

like image 552
Diggie Avatar asked Feb 03 '13 19:02

Diggie


People also ask

What is the shallow copy?

A shallow copy of an object is a copy whose properties share the same references (point to the same underlying values) as those of the source object from which the copy was made.

What is the difference between deep copy and shallow copy in C?

Deep copy stores copies of the object's value. Shallow Copy reflects changes made to the new/copied object in the original object. Deep copy doesn't reflect changes made to the new/copied object in the original object. Shallow Copy stores the copy of the original object and points the references to the objects.

Why do we use shallow copy?

In shallow copy, an object is created by simply copying the data of all variables of the original object. This works well if none of the variables of the object are defined in the heap section of memory.

Is struct shallow copy?

A shallow copy of an variable/object is a copy of an object, usually a container - for example, an array or a struct type such that the elements in both the copy and the original object are occupying the same memory addresses.


3 Answers

Because static fields are not part of the object. You could access them with ClassName.StaticValue. In fact, you CAN'T access them with ClassInstanceName.StaticValue.

like image 149
It'sNotALie. Avatar answered Sep 17 '22 20:09

It'sNotALie.


Static fields are shared by all the instances of a particular class.

like image 44
Andrew Savinykh Avatar answered Sep 16 '22 20:09

Andrew Savinykh


Because static members are class level members not instance level which mean that static members common for all instances of given type.

like image 35
Hamlet Hakobyan Avatar answered Sep 16 '22 20:09

Hamlet Hakobyan