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