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