Search code examples
c#attributescustom-attributesattributeusage

Creating custom attributes for methods that has specific signature


I created simple class has AttributeUsage attribute. When I tried to build I got error:

Attribute 'AttributeUsage' is only valid on classes derived from System.Attribute.

Then I made my class inherits from Attribute and everything is fine.

If I use AttributeUsage attribute then it forces me to inherit from Attribute class. My question is can I make attribute that forces methods to have specific signature?

Thanks for the help!


Solution

  • If I understand correctly: What you are looking for is a tool that controls the compilation by your attributes. You may check if stylecop or fxcop fit your needs. Alternatively you might extend Visual Studio to access the source code model. An extension may check the source code (see http://blogs.msdn.com/b/sqlserverstorageengine/archive/2007/03/02/using-visual-studio-s-code-model-objects-for-code-base-understanding.aspx), evaluates the attributes and generate compiler warnings, errors whatever you like.

    ===================================

    Original Answer:

    Answer: You just have to provide the corresponding constructor

    [AttributeUsage(AttributeTargets.All)]
    public class HelpAttribute : System.Attribute
    {
        // Required parameter
        public HelpAttribute(string url) 
        {
            this.Url = url;
        }
    
        // Optional parameter
        public string Topic { get; set; }
    
        public readonly string Url;
    
    
    }
    
    public class Whatever
    {
        [Help("http://www.stackoverflow.com")]
        public int ID { get; set; }
    
        [Help("http://www.stackoverflow.com", Topic="MyTopic")]
        public int Wew { get; set; }
    
        // [Help] // without parameters does not compile
        public int Wow { get; set; }
    }
    

    The allowed parameter types are liste at MSDN: http://msdn.microsoft.com/en-us/library/aa664615(v=vs.71).aspx

    Further reading: http://msdn.microsoft.com/en-us/library/aa288454(v=vs.71).aspx