Trebor
Trebor

Reputation: 813

Extend existing class and add clone() method C#

I have an existing vendor supplied class MyClass() that I cannot modify and I want to add a clone method to it. I thought the following would do it, but the MemberwiseClone() method isn't being found by the obj.

public static class MyExtensions 
{
    public static MyClass Clone(this MyCLass obj)
    {
        return (MyClass) obj.MemberwiseClone();
    }
}  

Any help would be greatly appreciated.

Upvotes: 1

Views: 260

Answers (1)

dcastro
dcastro

Reputation: 68750

That's because MemberwiseClone is a protected method, and is not accessible from MyExtensions.

The only way for you to perform this, is if MyClass is not marked as sealed. In that case, you can subclass it and use that type instead of the one provided by the vendor.

Please note that MemberwiseClone performs a shallow copy. Value type members are re-created entirely, but reference type members are not. The clone and the original object will be pointing to the same object.

If you cannot subclass MyClass, reconsider your need for a cloning method. If you really do need it, I see two possible options, none of which are advisable: using reflection to copy all fields or serializing/deserializing an instance (if the type supports serialization).

Upvotes: 6

Related Questions