views:

114

answers:

5

Hi there,

I was just wondering if an attribute can be applied to a static class, method or property in c#? Like,

[MyAttribute]
public static MyMethods(string str) ...

Thanks Ray.

+1  A: 

Yes. Probably. Just try and see.

I wonder why you'd doubt it.

Rotsor
+1  A: 

Yes you can apply attribute to static class,method,property.

example:

[MyAttribute("hello")]
      public static string SayHello(string str)
      {
         return str;
      }
Pranay Rana
+1  A: 

Yes, it can be applied.

Lukas Šalkauskas
+5  A: 

There are really two questions here

Is it possible for attributes in general to be applied to class, method's or properties?

Yes attributes can validly target any of these constructs (and many others)

Is it valid for a specific attribute to do so?

That depends on the specific attribute. Attributes can control which constructs they can be applied to via the AttributeTargets enum and hence make it illegal for a specific attribute to be applied to a specific construct.

For example the ParamArrayAttribute can only target parameters while the ObsoleteAttribute can target pretty much anything (except assemblies and maybe one other I'm missing)

JaredPar
Congrats on the 100k ;p
Marc Gravell
@Marc thanks! now for 200 :)
JaredPar
However, even `AttributeTarget` cannot make an attribute invalid on a *static* item but valid on a *non-static* one of the same kind...
Timwi
A: 

It depends on the Attribute if it can apply to a static class. Check out AttributeTarget. As such it is perfectly legal and allowed to decorate a static class or methods to with Attributes.

this. __curious_geek