I have seen lot of programs uses attributes.
[Attribute]
public class method()
{
}
I know attribute is nothing but a class derived from Attribute. I
still couldn't wrap my head around when to use and what it does during
run time. Can some one kindly point me to a detailed place where I can
read? Most of the examples are very simple and I don't see any use or
need of those. If you have time, could you kindly explain me what is
this?
An "attribute" simply represents any piece of information you may want to
store about a given entity (class, method, etc.) that can later be read by
3rd-party tools or the code itself at runtime. Why would you want to do
this? For the same reason you would store information about anything.
Someone might need it. Look at "System.ObsoleteAttribute" as one simple
example. By applying this to any method, you're telling the rest of the
world that the method is now considered obsolete. If you now call this
method in your program for instance, a compiler can detect that the method
is obsolete and display a warning for you. Or perhaps someone wants to write
a utility that will display all obsolete methods being called from your
program simply by reading the assembly itself (since the attribute info is
stored there). And what if you want to add your own information about some
entitry, say, which developer wrote a particular method for instance. You
can create your own "MethodAuthorAttribute" that takes the developers's
employee # (or some other appropriate ID) and this can appplied to every
method in your program. The attrbute can then be used for any number of
reasons. Perhaps you want to dump this to a log at runtime if an unexpected
exception is thrown (for diagnostic purposes). The code can determine which
method was involved and then dump the author's ID out by reading that
method's "MethodAuthorAttribute". Your help staff would then be able to
quickly determine which developer originally wrote the function (or maybe
your company's QA staff uses it during internal testing only). This example
is contrived of course but you get the idea. Have a look at the "Inheritance
Hierarchy" section under the "Attribute" class in MSDN
(
http://msdn.microsoft.com/en-us/library/system.attribute.aspx). These are
the native .NET attributes and many are used for obscure purposes but they
still fulfill their role, namely, they provide information about the
entities they apply to (to those who need it).