views:

146

answers:

3

Say I have the following hierarchy:

public class MyClass
{
  protected virtual void Method() { ... }
}

public class MySubClass : MyClass
{
  public new virtual void Method() { ... }
}

public class MySubSubClass : MySubClass
{
  // how do I reference the protected Method() to override it?
}

Is it possible to override the implementation of the protected Method() so that invocations from other methods defined in MyClass are dispatched to an implementation in MySubSubClass?

If not possible, it'd be nice to be enlightened as to why.

A: 

Yes. You can use "new" keyword to reintroduce any method you want. From that point on, every call to the the "newed" method will be addressed to the new implementation.

In this case, any call to Method() originated from MyClass will use the MySubSubClass implementation as long as the object in question is of type MySubSubClass

Ciwee
I'm not sure I'm following you. I understand I can use `new` to redefine a particular method name. I did that in MySubClass. But since it's `new`, MyClass isn't aware of it and will *not* dispatch to it.
gWiz
+7  A: 

If you're attempting to override the version of Method defined in MyClass then the answer is you cannot. The definition in MySubClass hides this implementation from you and it's not possible for you to further override it.

JaredPar
Stupid followup? If he's overriding it, does it matter since which he replaces since he is replacing it anyways?
Matt
@Matt: Yes, despite having the same name they are two very different functions. If you call `((MyClass)this).Method()` it will run different code from `this.Method()`.
280Z28
He can only hide the method in MyClass, not override it - if an instance of MySubSubClass was cast to MyClass, then the Method() called can only be the one in MyClass, it won't be dispatched virtually
thecoop
Thank you. Do you have any explanation as to why explicit interface-style overriding isn't possible? Is this the result of something "philosophical" about OOP?
gWiz
@gWiz, IIRC it's a CLR limitation so it's not a design decision C# has control over.
JaredPar
A: 

As @Jared said, you cannot. I can only assume that you're trying to avoid using new again because you want proper virtual handling. The only way you're going to manage this is by getting rid of the public new version of Method() and naming it something else. new completely hides any version of the method you're redeclaring that may exist in ancestor objects.

Donnie
Thank you, upon reading Jared's answer, renaming MySubClass.Method is the same conclusion I came to. By the way, I'm not trying to avoid `new`. I'm not sure how another usage of `new` could have helped. I just want to change the implementation of a method in the super-superclass that is hidden by the superclass.
gWiz