Why use attributes?

  • Thread starter Thread starter sourabh
  • Start date Start date
S

sourabh

Hi
I have a very basic question here - why do we need attributes or basically
how we decide when to use attributes?
I have used a lot of .net inbuilt attributes, but have not been really able
to put this great feature to use by defining custom attributes. I know how
to use them but the bigger question is when should we use them.

Perhaps this might be a very simple question to the .net world. All help is
welcome.

Thanks
Sourabh
 
sourabh said:
Hi
I have a very basic question here - why do we need attributes or basically
how we decide when to use attributes?
I have used a lot of .net inbuilt attributes, but have not been really able
to put this great feature to use by defining custom attributes. I know how
to use them but the bigger question is when should we use them.

Attributes are a way to package information *about* your code with your
code. Programs can read this information using reflection and use that
information to interact with your code in interesting ways.

A good example of when you might create and use a custom attribute is
Jon Skeet's micro-benchmark framework:

http://www.yoda.arachsys.com/csharp/benchmark.html

In that framework, he defines a custom attribute, 'BenchmarkAttribute'.

In the code that you want benchmarked, you simply add the [Benchmark]
attribute marker to each method that you want the benchmark framework to
time. When the benchmark framework runs, it looks for all the methods
with a particular signature that are marked with the BenchmarkAttribute,
and it times the execution of those methods.
 
Attributes add some information about the code, as Mike has suggested, but
it gets more involved than this.

Try this:
Go to SourceForge.com and download nUnit. Install the code and look at how
nUnit can help you with unit tests. Basically any bit of code set up with
the proper attribute will be run, via reflection, in your compiled assembly.
This, to me, best illustrates the use of attributes.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

**********************************************************************
Think Outside the Box!
**********************************************************************
 
Back
Top