DateTime
is a value type, like int
. So, it will be copied by the MemberwiseClone().
Does memberwiseclone copy DateTime, or must it be explicitly set?
-
26-06-2022 - |
Question
I'm implementing ICloneable
on a ton of custom objects. Some of the objects have a type of DateTime
, which is a struct value. I know this value can be copied using newDateTime = oldDateTime
, but if I use MemberwiseClone()
on my object, does it automatically copy the DateTime
objects? I assume not because DateTime
does not implement ICloneable
itself.
Solution
OTHER TIPS
Since DateTime
is value type, it will be copied.
Object.MemberwiseClone Method - MSDN
The MemberwiseClone method creates a shallow copy by creating a new object, and then copying the nonstatic 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. If a field is 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.