What is the purpose of Attributes in C#?
How do I know which attribute have to use for particular functionality?
How can I add them dynamically in c#?
What are custom attributes ?
Attributes provide a powerful method of associating metadata, or declarative information, with code (assemblies, types, methods, properties, and so forth). After an attribute is associated with a program entity, the attribute can be queried at run time by using a technique called reflection.
The __attribute__ directive is used to decorate a code declaration in C, C++ and Objective-C programming languages. This gives the declared code additional attributes that would help the compiler incorporate optimizations or elicit useful warnings to the consumer of that code.
Attributes are modern ways in C++ to standardize things if their code runs on different compilers. Attributes are used to provide some extra information that is used to enforce conditions (constraints), optimization and do specific code generation if required.
Attributes are meant to add additional information about a class, function, etc. Compilers sometimes do special things when they see an attribute. Other attributes are looked at by libraries while the program is running.
Start by looking at the documentation for the functionality you want. It should list what attributes are necessary.
No. Attributes can only be applied before the code is compiled.
That is just an attribute you created yourself as opposed to one that came with .NET.
When you write your code you answer the "what?" question:
etc. Attributes add another dimension to this question. They answer the "how?" question. And the reply to the "how?" question may be important for IDE,
[Browsable(false)]
public string NotImportantField { get; set; } // property which will not be displayed in VS
for the compiler
[ThreadStatic]
private static RequestContext context; // field which will be different for every thread
or for another code which analyzes yours via reflection.
[XmlIgnore]
public string NotSerializableField { get; set; } // property which will not be xml-serialized
you might want to define custom attributes, if your assemblies, classes, fields, methods, etc. will be analyzed or invoked via reflection (which is often the case for example with inversion of control containers and aspect-oriented programming). Such attribute might (and often are the only way to) instruct the invoker or analyzer to behave differently depending on such attribute presence or its properties.
About your first question, well, how we know which method to call for a particular result? One of the advantages of being a .NET developer is that everything is documented pretty thoroughly. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With