1

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!

Dilshod
  • 3,189
  • 3
  • 36
  • 67

1 Answers1

0

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

Fried
  • 1,323
  • 12
  • 21
  • Sorry for my bad English. On my question I was trying to ask is: When I make attribute, that attribute must force method to have specific signature. I am not worried about attribute's constructor(signature). In the example you gave me is: string url is a required parameter and Topic is named parameter. Here is example: When I use Help attribute on my method, that Help attribute must force method to have string and int parameter. – Dilshod Jul 26 '13 at 12:37
  • Let me try to rewrite your question: Is it possible to write an Attribute to control a method`s signature? – Fried Jul 26 '13 at 20:05