Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call MemberwiseClone()?

Tags:

c#

object

clone

I'm confused about how to use the MemberwiseClone() method. I looked the example in MSDN and they use it trough the this keyword.

Why I can not call it directly as other objects' methods like 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?

like image 605
mjsr Avatar asked May 19 '11 23:05

mjsr


2 Answers

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

like image 141
SLaks Avatar answered Nov 01 '22 12:11

SLaks


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

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

And call it like:

var cloned = User.ShallowCopy<User>();
like image 31
Esteban Avatar answered Nov 01 '22 11:11

Esteban