Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 349
ALOR Avatar asked May 23 '26 14:05

ALOR


1 Answers

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

like image 161
Nader Shirazie Avatar answered May 25 '26 04:05

Nader Shirazie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!