Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Wrapping methods in other methods

Tags:

c#

perl

aop

moose

Is there a way to wrap methods in other methods transparently in C#? I want to achieve what is done by Moose's around functionality: http://search.cpan.org/perldoc?Moose::Manual::MethodModifiers

EDIT: And by transparent I mean without modifying the original method.

like image 793
rpkelly Avatar asked Feb 01 '11 21:02

rpkelly


2 Answers

I think you're looking for what's termed Aspect Oriented Programming. There are many C# libraries to help with this. One is called PostSharp (The free version of PostSharp supports this functionality). Here is an example similar to the moose example. This creates a Trace Attribute which you can use on other methods to tack on this extra functionality:

[Serializable]
public class TraceAttribute : OnMethodBoundaryAspect
{

    public override void OnEntry( MethodExecutionArgs args )
    {
        Trace.WriteLine("about to call method");
    }

    public override void OnExit(MethodExecutionArgs args) 
    { 
       Trace.WriteLine("just finished calling method"); 
    }
 }

You would add it to method "Foo" by placing the Trace attribute right before it:

[Trace]
public void Foo() { /* ... */ }

Now when Foo executes, the above OnEntry method will run before it, and OnExit will run right after.

like image 164
Joel Beckham Avatar answered Sep 18 '22 17:09

Joel Beckham


Indeed, they're called "delegates" in .NET. See:

  • http://alexdresko.com/2010/07/25/using-idisposable-objects-responsibly-the-easy-way/
  • http://alexdresko.com/2010/07/27/using-delegates-to-eliminate-duplicate-code/

for help.

like image 33
Alex Dresko Avatar answered Sep 20 '22 17:09

Alex Dresko