Ray
Ray

Reputation: 12441

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) ...

Upvotes: 6

Views: 5677

Answers (5)

JaredPar
JaredPar

Reputation: 754893

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)

Upvotes: 6

this. __curious_geek
this. __curious_geek

Reputation: 43207

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.

Upvotes: 0

Lukas Šalkauskas
Lukas Šalkauskas

Reputation: 14361

Yes, it can be applied.

Upvotes: 1

Pranay Rana
Pranay Rana

Reputation: 176916

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

example:

[MyAttribute("hello")]
      public static string SayHello(string str)
      {
         return str;
      }

Upvotes: 2

Rotsor
Rotsor

Reputation: 13783

Yes. Probably. Just try and see.

I wonder why you'd doubt it.

Upvotes: 0

Related Questions