Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interrogate method attributes via a delegate?

Tags:

c#

I have a method with a custom attribute. If I have a delegate that refers to this method can I tell if the method referred to by the delegate has the attribute or not?

like image 244
djp Avatar asked Jan 21 '10 04:01

djp


2 Answers

Use the GetCustomAttributes method of the Method property of the delegate. Here's a sample:

    delegate void Del();

    [STAThread]
    static void Main()
    {
        Del d = new Del(TestMethod);
        var v = d.Method.GetCustomAttributes(typeof(ObsoleteAttribute), false);
        bool hasAttribute = v.Length > 0;
    }

    [Obsolete]
    public static void TestMethod()
    {
    }

If the method has the attribute the var v will contain it; otherwise it will be an empty array.

like image 93
Michael Bray Avatar answered Oct 09 '22 13:10

Michael Bray


I'm not sure if this is the general case, but I think so. Try the following:

class Program
{
    static void Main(string[] args)
    {
        // display the custom attributes on our method
        Type t = typeof(Program);
        foreach (object obj in t.GetMethod("Method").GetCustomAttributes(false))
        {
            Console.WriteLine(obj.GetType().ToString());
        }

        // display the custom attributes on our delegate
        Action d = new Action(Method);
        foreach (object obj in d.Method.GetCustomAttributes(false))
        {
            Console.WriteLine(obj.GetType().ToString());
        }

    }

    [CustomAttr]
    public static void Method()
    {
    }
}

public class CustomAttrAttribute : Attribute
{
}
like image 31
Dathan Avatar answered Oct 09 '22 12:10

Dathan