Reputation: 209
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.
Upvotes: 1
Views: 193
Reputation: 56934
Yes it is possible, but not as is.
You can do that by using Aspect Oriented Programming. PostSharp is a framework that allows you to do that; it allows you to 'weave' aspects into the code at compile time.
[Serializable]
public class TestAttribute : OnMethodInvocationAspect
{
public override void OnInvocation()
{
Console.WriteLine ("TestAttribute called");
base.OnInvocation();
}
}
Upvotes: 0
Reputation: 1062745
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).
Upvotes: 2
Reputation: 9101
I don't believe so - Attributes are only read by things reflecting over the code, they aren't called during normal execution.
Upvotes: 1