C#: How to create an attribute on a method triggering an event when it is invoked?

Created : 7/11/2022

Question

Is there a way in C# or .NET in general to create an attribute on a method which triggers an event when the method is invoked? Ideally, I would be able to run custom actions before and after the invocation of the method.

I mean something like this:

[TriggersMyCustomAction()]
public void DoSomeStuff()
{
}

I am totally clueless how to do it or if it possible at all, but System.Diagnostic.ConditionalAttribute might do a similar thing in the background. I am not sure though.

EDIT: I forgot to mention that due to the circumstances of my specific case, performance is not really an issue.

Questioned by : Tamas Czinege

Answer

The only way I know how to do this is with PostSharp. It post-processes your IL and can do things like what you asked for.

Answered by : Community