2

Possible Duplicate:
Use reflection to invoke an overridden base method

Normally I can call my base class from within an overridden method like this:

public override void Foo(Bar b)
{
    base.Foo(b);
}

How can I make this same call with reflection?

Edit: to explain a bit, I'm trying to use AOP to guard my library's entry points from uninitialized operation (in my case there is no "initialize" call prior to the library's usage). So the relevant calls will technically end up inside the class (by virtue of the AOP), but the pre-compiled code will be written in a separate class. In other words, I want the following advice applied to all of my entry points:

if (!initialized)
    return base.<method>(<arguments>);

I suppose the IL trick shown in Use reflection to invoke an overridden base method will work for me - I was just hoping there was something cleaner in my case since it feels more legitimate.

Community
  • 1
  • 1
ladenedge
  • 13,197
  • 11
  • 60
  • 117
  • @HatSoft: saw that, but I think it's a bit different. He's trying to call a base class's overridden method from outside the class. – ladenedge Jul 23 '12 at 20:08
  • So you want to reflectively invoke the parent method from inside code for a derived instance? Why do you think you need to do that? – KeithS Jul 23 '12 at 20:11
  • you really really really don't want to have an AOP inject reflection calls into all of your methods... unless of course you are competing with somebody else to see who can create the slowest possible program – Robert Levy Jul 23 '12 at 20:28

1 Answers1

2

EDIT: OK, so a bit of clarification; you're not trying to call the base class's implementation from outside either class. Instead, from within the overridden class, you want to reflectively call the parent method's implementation.

... Why? Your object statically knows what it is, and therefore statically knows what its base class is. You can't have two base classes, and you can't dynamically "assign" a base class to a pre-existing child class.

To answer your question, you can't. Any attempt to reflectively call "Foo" using the current instance will infinitely recurse, because the invocation of a MethodInfo makes the method call as if it were coming from outside ('cause it is), and so the runtime will obey inheritance/overriding behaviors. You would have to use the IL hack from the related question.

KeithS
  • 70,210
  • 21
  • 112
  • 164
  • Ah, interesting point on the recursion. That's a fly in the ointment. – ladenedge Jul 23 '12 at 20:26
  • Apparently this is [not possible through some PostSharp trick](http://support.sharpcrafters.com/discussions/questions/20-call-an-overridden-base-classs-method-in-postsharp-aspect) either. Ah well, thanks for your help! – ladenedge Jul 23 '12 at 20:52