How can I call MemberwiseClone ()?

I am confused about how to use MemberwiseClone() method. I looked at the example on MSDN and used it through the this .

Why can't I call it directly, like methods of other objects, such as GetType() or ToString() ? Another related method that does not appear is ShallowCopy() .

If they are part of the Object class, why can't I see them?

+8
object c # clone
source share
2 answers

The MemberwiseClone() function is protected , so you can only access it with a qualifier of your own type.

+10
source share

Here is an example, this is what I have done, and no problems so far.

 public class ModelBase { public T ShallowCopy<T>() where T : ModelBase { return (T)(MemberwiseClone()); } } 

And call it that:

 var cloned = User.ShallowCopy<User>(); 
+6
source share

All Articles