Search code examples
c#perlmooseaop

C#: Wrapping methods in other methods


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.


Solution

  • 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.