tags:

views:

1403

answers:

2

I'm trying to use .MemberwiseClone on a custom class of mine, but it throws up this error:

Cannot access protected member 'object.MemberwiseClone()' via a qualifier of type 'BLBGameBase_V2.Enemy'; the qualifier must be of type 'BLBGameBase_V2.GameBase' (or derived from it)

What does this mean? Or better yet, how can I clone an 'Enemy' class?

+6  A: 

Within any class X, you can only call MemberwiseClone (or any other protected method) on an instance of X. (Or a class derived from X)

Since the Enemy class that you're trying to clone doesn't inherit the GameBase class that you're trying to clone it in, you're getting this error.

To fix this, add a public Clone method to Enemy, like this:

class Enemy : ICloneable {
    //...
    public Enemy Clone() { return (Enemy)this.MemberwiseClone(); }
    object ICloneable.Clone() { return Clone(); }
}
SLaks
But I thought MemberwiseClone was a method of Object, which afaik all classes are dervied from?
Motig
Yes, but you can't call a different class's protected method unless it inherits from _you_. Otherwise, you'd be able to call any protected member (including `MemberwiseClone`) on any class simply by inheriting from that class. This would make `protected` almost useless.
SLaks
"protected" is another way of saying: only the class itself knows when MemberwiseClone() is the proper thing to do. It rarely is, google "deep copy".
Hans Passant
A: 

Sorry I don't have enough reputation score so I can't comment.

Can anyone explain it in an easier way please, I don't understand why we cannot use MemberWiseClone()

Because All classes inherit from Object, so even if MemberWiseClone() is protected, it should be usable by the other classes...I am confused!!! Am I missing something??

Bon_chan
For a similar explanation look here: http://blogs.msdn.com/b/ericlippert/archive/2005/11/09/why-can-t-i-access-a-protected-member-from-a-derived-class.aspx. With `MemberwiseClone`, you're trying to access a `protected` method in another type's separate class heirarchy, which isn't allowed (as that essentially makes `protected` useless)
thecoop