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.
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.
Yes you can apply attribute to static class,method,property.
example:
[MyAttribute("hello")]
public static string SayHello(string str)
{
return str;
}
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)
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.