-1

I have a subclass which overrides a virtual method in its base class which is abstract. Can i access the virtual method of the base class via an subclass instance?

Thanks.

For example

public abstract class BaseClass{
    public virtual void MyMethod(){...}
} 

public Class SubClass{
    public override void MyMethod(){...}
} 

public static void Main(string[] args)
{
    SubClass MyObject = new SubClass();
    MyObject.MyMethod(); // need a way to refer to BaseClass.MyMethod, instead of SubClass.MyMethod().
}
Tim
  • 1
  • 141
  • 372
  • 590
  • 1
    It wouldn't make sense to override the method in the SubClass if this is your use case. – Kevin Smith Jun 06 '17 at 22:57
  • I didn't write both classes. – Tim Jun 06 '17 at 22:59
  • 1
    If you own the code I'd personally change due to bad object design but if you insist, you can do some crazy stuff to still execute it, check out this - https://stackoverflow.com/a/14415506/4079967 – Kevin Smith Jun 06 '17 at 23:04

2 Answers2

1

Yes.

public class SubClass : BaseClass
{
    public override void MyMethod()
    {
        base.MyMethod();
    }
} 
Scott Hannen
  • 27,588
  • 3
  • 45
  • 62
1

No, there is no reasonable way to call just base virtual method from outside the class.

The easiest way if you control derived class is to expose base.MyMethod via some other method. If you can't change derived class I think you are out of luck.

Even if you can try to get exact method via reflection and invoke it with given instance, it will still perform virtual call to derived method.

var d = new SubClass();
var m = typeof(BaseClass).GetMethod("MyMethod");
m.Invoke(d, new object[0]); // calls SubClass.MyMethod
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • (Not so reasonable way is available in https://stackoverflow.com/questions/4357729/use-reflection-to-invoke-an-overridden-base-method - thanks [Kevin Smith](https://stackoverflow.com/users/4079967/kevin-smith) for the link - closed as dup) – Alexei Levenkov Jun 06 '17 at 23:10