Suppress virtual call mechanism

D

Dilip

This must be fairly straightforward as I used to do this quite often
in C++ but I seem to be missing something really obvious. How do I
force the code to call Foo.DoThis() inside Foo.CallIntoDoThis(), even
though the current instance is of type Bar (and hence the call always
dispatches to Bar.DoThis())?

public abstract class Baz
{
public abstract void DoThis();
}

public class Foo : Baz
{
public override void DoThis()
{
Console.WriteLine("Foo.DoThis");
}

public void CallDoThis()
{
DoThis();
// how do I force a call to Foo.DoThis() here???
((Foo)this).DoThis(); // this doesn't work
}
}

public class Bar : Foo
{
public override void DoThis()
{
Console.WriteLine("Bar.DoThis");
}

public void CallIntoFoo()
{
CallDoThis();
}
}

class Program
{
static void Main(string[] args)
{
Bar b = new Bar();
b.CallIntoFoo();
}
}
 
D

Dilip

The usual pattern would be to require the _override_ to manage it.  That  
is, in class Bar:

     public override void DoThis()
     {
         Console.WriteLine("Bar.DoThis");
         base.DoThis();
     }

You could implement the literal behavior you're showing by making  
Foo.DoThis() call a non-virtual helper method that the Foo class knows  
about:

     public override void DoThis()
     {
         _DoThisImpl();
     }

     public void CallDoThis()
     {
         DoThis();
         // how do I force a call to Foo.DoThis() here???
         _DoThisImpl();
     }

     private void _DoThisImpl()
     {
         Console.WriteLine("Foo.DoThis");
     }

But I don't like that pattern much, at least not in this case, because you  
could conceivably wind up calling the same method twice (if you have an  
instance of Foo, not Bar).  That seems likely to be wrong, but of course  
only you would know for sure if that's really what you meant to do.

Pete

Pete

Thanks very much. I knew the usual base.DoThis() pattern but in my
case I wanted the literal behaviour as I laid it out in my post.
Thankfully your reply gave me an idea and I ended up implementing it
successfully.

Cheers!
 
G

gerry

- have Bar call its base implemenation if DoThis :

public class Bar : Foo
{
public override void DoThis()
{
base.DoThis();
Console.WriteLine("Bar.DoThis");
}

public void CallIntoFoo()
{
CallDoThis();
}
}


- or - don't depend on the derived class calling its base implementation and
use an private Foo method :

public class Foo : Baz
{
private void FooDoThis()
{
Console.WriteLine("Foo.FooDoThis");
}

public void CallDoThis()
{
DoThis();
FooDoThis();
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top