I've created a simple Attribute:
[AttributeUsage(AttributeTargets.Method)]
public class InitAttribute : System.Attribute
{
public InitAttribute()
{
Console.WriteLine("Works!");
}
}
and I apply it to a simple method:
static class Logger
{
public static string _severity;
public static void Init(string severity)
{
_severity = severity;
}
[Init()]
public static void p()
{
Console.WriteLine(_severity);
}
}
What is going on is pretty straightforward. Only, I expect the attribute to perform an action (printing "Works!"), but this does not happen.
Additionally, printing "Works!" is of course just for debugging purposes: I'd like to access the instance's property _severity
(to check if is != null
, for example), but everything I keep reading about regarding attributes (that is pretty new to me) is about accessing the class' methods or properties and so on via reflection. Once I've evaluated _severity
, how can I modify the behavior of the decorated method (in this case, raise an exception "Logger is not initialized" and do not execute it)?
Any help appreciated.
If you need to perform an action as control enters a method, you should look at aspect-oriented programming and frameworks such as PostSharp. Attributes are not designed to perform anything by themselves. They are just a bunch of data (or metadata if you will) attached to stuff in IL assemblies that can be queried at runtime.