Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my .NET Attribute not perform an action?

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 streight-forward. Only, I expect the attribute to perform an action (printing Works!), but this does not happen.

Addictionally, 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 attributes (that are 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, rise an exception "Logger is not initialized" and do not execute it)?

Any help appreciated.

like image 275
pistacchio Avatar asked Jul 22 '09 12:07

pistacchio


1 Answers

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.

like image 195
mmx Avatar answered Oct 25 '22 01:10

mmx