andreyk2 Hohlov
andreyk2 Hohlov

Reputation: 749

Why MemberwiseClone() can not be used directly, like other inherited methods of Object class? (For shallow copy)

Lets say I have some custom type:

public class MyClass
{
   public int Age;
}

According to MS documentation here, all classes in .NET are derived from Object, and every method defined in the Object class is available in all objects in the system

Since Object.MemberwiseClone() is part of object class, why I can't do shallow copy just by calling it form instance on my custom class, like "Equals(), GetHashCode(), etc? Why I can't do something like this:

class Program
{
     static void Main(string[] args)
     {
         MyClass myClass = new MyClass();
         MyClass myClassCopy = (MyClass)myClass.MemberwiseClone();  //Not working!
     }
}

Instead, in all the examples I have see, I need to implement some shallow copy method explicitly like:

public class MyClass
{
    public int Age;
    public MyClass ShallowCopy()
    {
        return (MyClass)MemberwiseClone();
    }
}

And only then, I can call to this method ShallowCopy().

[EDIT]

I think this question here explains the point: Why is MemberwiseClone defined in System.Object protected? I was need to ask what it the rationale of making Object.MemberwiseClone() as private, and the main reason is: The problem here is that MemberwiseClone just blindly copies the state. In many cases, this is undesirable

Upvotes: 2

Views: 1709

Answers (2)

zalky
zalky

Reputation: 887

This is because protected members of a base class can only be accessed from derived classes' scope.

The reason this part of the following code;

MyClass myClassCopy = (MyClass)myClass.MemberwiseClone();

cannot access the 'MemberwiseClone' method is, simply 'myClassCopy' object is outside of the derived class scope, that's why it can't be reached through object.

Upvotes: 0

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239764

It's a protected method - presumably to allow each class's implementation to decide on whether or not memberwise cloning makes sense and, if so, how to expose it to callers.

Upvotes: 3

Related Questions