Is there any way to write a custom class which extends .NET Attribute class so that I can apply that class on a method and .NET Framework calls my class constructor before executing that method. Here is the example
public class TestAttribute : Attribute
{
public TestAttribute()
{
Console.WriteLine("Called");
}
}
class Program
{
static void Main(string[] args)
{
TestMethod();
}
[TestAttribute()]
public static void TestMethod()
{
}
}
I want when TestMethod is called, framework will execute TestAttribute() constructor.
In regular .NET attributes don’t cause magic invocation, except for a very limited set of system attributes (security etc). The rest are applied only by inspection through reflection, which has to be done explicitly.
You might look at PostSharp (now renamed into a commercial product).