Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is MemberwiseClone defined in System.Object protected?

Tags:

.net

I'm wondering why MemberwiseClone is defined as protected. This means that only derived types can access it. What is the problem if it was defined as public?

like image 708
hadi Avatar asked Jul 17 '10 16:07

hadi


People also ask

How does MemberwiseClone work?

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.


2 Answers

Pavel Minaev's answer from another discussion:

Others have already explained about MemberwiseClone, but no-one gave the explanation of why it is protected. I'll try to give the rationale.

The problem here is that MemberwiseClone just blindly copies the state. In many cases, this is undesirable. For example, the object might have a private field which is a reference to a List. A shallow copy, such as what MemberwiseClone does, would result in new object pointing to the same list - and the class may well be written not expecting the list to be shared with anyone else.

Or an object can have some sort of ID field, generated in constructor - again, when you clone that, you get two objects with the same ID, which may lead to all kinds of weird failures in methods assuming that ID is unique.

Or say you have an object that opens a socket or a file stream, and stores a reference to that. MemberwiseClone will just copy the reference - and you can imagine that two objects trying to interleave calls to the same stream isn't going to end well.

In short, "cloning" is not a well-defined operation for arbitrary objects. The fact that memberwise operator= is provided for all classes by default in C++ is more of a nuisance, as all too often people forget that it's there, and do not disable it for classes for which copying doesn't make sense, or is dangerous (and there are surprisingly many such classes).

like image 127
dante Avatar answered Sep 17 '22 14:09

dante


  • A lot of things don't make sense to be cloned; anything that talks to an unmanaged handle, for example
  • Most objects do not need a clone facility
  • Deep-copying something properly is really hard if you go outside of a few simple cases
  • In many cases, there are better metaphors than blind clones
  • Manually adding a clone facility to your types that need it is trivially easy

To me, then, it is a no-brainer that this should not be added to the public API by default.

like image 30
Marc Gravell Avatar answered Sep 19 '22 14:09

Marc Gravell