Search code examples
c#.netreflectionattributescross-cutting-concerns

C# Attribute to modify methods


all. Maybe i've not googled enough, but i can't find any example on this question.

It is possible in C# to create an custom attribute which, applied to a class, modifies all of its methods? For example, adds Console.WriteLine("Hello, i'm modified method"); as a first line (or it's IL equivalent if it's done at runtime)?


Solution

  • Yes, you can do this, but no, its not built in to C#. As Eric says, this technique is known as Aspect Oriented Programming.

    I've used PostSharp at work, and it is very effective. It works at compile time, and uses IL-weaving, as opposed to other AOP techniques.

    For example, the following attribute will do what you want:

    [Serializable]
    [MulticastAttributeUsage(MulticastTargets.Method | MulticastTargets.Class,
                             AllowMultiple = true,
                             TargetMemberAttributes = MulticastAttributes.Public | 
                                                      MulticastAttributes.NonAbstract | 
                                                      MulticastAttributes.Managed)]
    class MyAspect : OnMethodInvocationAspect
    {
        public override void OnInvocation(MethodInvocationEventArgs eventArgs)
        {
            Console.WriteLine("Hello, i'm modified method");
    
            base.OnInvocation(eventArgs);
        }
    }
    

    You simply apply MyAspect as an attribute on your class, and it will be applied to every method within it. You can control how the aspect is applied by modifying the TargetmemberAttributes property of the MulticastAttributeUsage property. In this example, I want to restrict it to apply only to public, non-abstract methods.

    There's a lot more you can do so have a look (at AOP in general).