Search code examples
c#attributesprivate-membersattributeusage

Custom Attribute - Set Attribute Usage for Only Private Members


I creating a custom attribute and I would like to the set the AttributeUsage (or maybe some other attribute in the attribute class) so that I my attribute can only be used in private methods, is that possible?

Thanks in advance for the answers!


Solution

  • There is no such feature available in C# (as of 4.0) that allows you to restrict attribute usage based on a member's accessibility.

    The question would be why do you want to do that?

    Because given below attribute,

    [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
    sealed class MethodTestAttribute : Attribute
    {
        public MethodTestAttribute()
        { }
    }
    

    and below class,

    public class MyClass
    {
        [MethodTest]
        private void PrivateMethod()
        { }
    
        [MethodTest]
        protected void ProtectedMethod()
        { }
    
        [MethodTest]
        public void PublicMethod()
        { }
    }
    

    You can easily get attributes of private methods using following code:

    var attributes = typeof(MyClass).GetMethods().
                     Where(m => m.IsPrivate).
                     SelectMany(m => m.GetCustomAttributes(typeof(MethodTestAttribute), false));