Is there any way to call the CallCommonCode() attribute constructor automatically when CodedMethod() is called?
using System;
[AttributeUsage(AttributeTargets.Method|AttributeTargets.Struct,
AllowMultiple=false,Inherited=false)]
public class CallCommonCode : Attribute
{
public CallCommonCode() { Console.WriteLine("Common code is not called!"); }
}
public class ConcreteClass {
[CallCommonCode]
protected void CodedMethod(){
Console.WriteLine("Hey, this stuff does not work :-(");
}
public static void Main(string[] args)
{
new ConcreteClass().CodedMethod();
}
}
No, because the attribute exists independently of the function. You can scan for the attribute or you can execute the function, but you can’t do both at the same time.
The point of an attribute is just to tag stuff with extra metadata, but it’s not strictly speaking actually part of the code itself.
What you would normally do in this situation is scan for the tag on the function, and if it goes against your business logic, you would throw some sort of exception. But in general, an attribute is just a ‘tag’.