0

Are there any ways to inject functionality into methods? Say you have a class that inherits from an abstract class, is there any way the abstract class can do something at the start of every method call, without the abstract class already knowing about all the methods, and without the inherited class having to call something on the abstract class at the start of every method?

Maybe it's easier to explain with an example. Let's say I have these classes:

public abstract class Foo {
    SomeMagicStuff() {
        Console.WriteLine("Hello from Foo");
    }
}

public class Bar : Foo {
    public void Hello() {
        Console.WriteLine("Hello from Bar");
    }
    public void Hello2() {
        Console.WriteLine("Another hello from Bar");
    }

    public static void Main() {
        Hello();
        Hello2();
    }
}

Is there any way to have Foo inject some functionality into all methods of Bar, even though Foo has no knowledge of all the methods of Bar? For this example I would then want to output to be:

Hello from Foo
Hello from Bar
Hello from Foo
Another hello from Bar

Is this even possible?

TheHvidsten
  • 4,028
  • 3
  • 29
  • 62
  • 1
    It sounds like you're describing [Aspect-oriented Programming](https://en.wikipedia.org/wiki/Aspect-oriented_programming) concepts. – Jamiec Jun 16 '15 at 11:09
  • As @Jamiec says, what you're trying to do can be accomplished via IL-weaving. Postsharp is a popular tool. – LiamK Jun 16 '15 at 11:12
  • Similar question: [C# Attribute to trigger an event on invoking a method](http://stackoverflow.com/questions/226420/c-sharp-attribute-to-trigger-an-event-on-invoking-a-method) – Mariano Desanze Jun 16 '15 at 11:14

1 Answers1

0

After a lot of digging I came to the conclusion that this is impossible in vanilla C#.Net.

This is indeed called Aspect Oriented Programming as @Jamiec describes.

PostSharp has methods to do exactly what I wanted (even though this tool is licensed, they do have a free version with this functionality enabled). They do, however, have some limitations (which is more a C# limitation than PostSharp limitation) so I couldn't use that the way I wanted either. In the end I wound up doing something more old-school.

Future visitors to this question can read about AOP and Postsharp and decide if that is the way to go for them.

Community
  • 1
  • 1
TheHvidsten
  • 4,028
  • 3
  • 29
  • 62
  • Note that PostSharp in particular has general meta-programming capabilities, so there are quite often ways to bypass this and other C# limitations. Depends on the problem, but PostSharp aspects can execute any code when the assembly is compiled (even if they are declared in the same assembly). – Daniel Balas Jun 25 '15 at 11:32