Mubashir Khan Mubashir Khan - 3 years ago 168
C# Question

Usage of targets on events using attributes

There are three possible attribute targets when using attributes on events (field defined events) and those are event, field and method. I understand the usage of event and field target, but where does the method target apply.

for example

[AttributeUsage(AttributeTargets.All,AllowMultiple=false,Inherited=true)]
internal class TestAttribute : Attribute
{
}
internal class Test
{
[event: Test]
[field: Test]
[method: Test]
public event Action action;
}

Answer Source

As far as I can tell, it's applied to the "add" and "remove" methods generated by the compiler (the methods which perform the subscription/unsubscription):

using System;
using System.Reflection;
using System.Runtime.CompilerServices;

[AttributeUsage(AttributeTargets.All,AllowMultiple=false,Inherited=true)]
internal class TestAttribute : Attribute
{
}
internal class Test
{
    [event: Test]
    [field: Test]
    [method: Test]
    public event Action action;

    static void Main() 
    {
        MethodInfo method = typeof(Test).GetEvent("action")
                                        .GetRemoveMethod(); // Or GetAddMethod
        Console.WriteLine(method.IsDefined(typeof(TestAttribute), true));
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download