Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, can an attribute be applied to a static class, method or property?

Can an attribute be applied to a static class, method or property in c#? Like:

[MyAttribute]
public static MyMethods(string str) ...
like image 748
Ray Avatar asked Jun 16 '10 05:06

Ray


1 Answers

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)

like image 157
JaredPar Avatar answered Nov 10 '22 11:11

JaredPar