Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force calling the base method from outside a derived class

I have two classes:

public class MyBase
{
    public virtual void DoMe()
    {

    }
}

public class MyDerived:MyBase
{
    public override void DoMe()
    {
        throw  new NotImplementedException();
    }
}

And I have the following code to instantiate MyDerived:

        MyDerived myDerived=new MyDerived();

The thing is how to call DoMe of the base class? If I use myDerived.DoMe(), then the derived method wil be called, resulting in an exception. I tried to cast myDerived to MyBase, yet it is still the derived version of the method that gets called.

Edit: As mentioned in the below comment, I can't change eitehr MyDerived or MyBase because they are not my code.

like image 894
Graviton Avatar asked Jan 13 '09 04:01

Graviton


1 Answers

There's a solution, but it's ugly: use reflection to get the base-class method, and then emit the IL necessary to call it. Check out this blog post which illustrates how to do this. I've successfully used this approach it to call the base class's implementation of a method when all I have is a reference to a derived class which overrides that method.

like image 154
Justin Grant Avatar answered Oct 06 '22 00:10

Justin Grant