Tools Used: Visual C# .NET
What are Attributes?
Here is a quote about what an attribute is all about:
"Attributes provide a powerful method of associating declarative information with C# code (types, methods, properties, and so forth). Once associated with a program entity, the attribute can be queried at run time and used in any number of ways." - MSDN
Attributes are classes that allow you to add additional information to elements of your class structure.
The information from the attribute can later be obtained by using Reflection. See article on reflection on this site. In this article, we will show you how to add stereotypes to your method. A stereotype is a way to describe a specific category for a design element and is a term that comes from UML. Our stereotype attribute provides two strings to describe our methods, a stereotype string and a description string. Below is the code for declaring our custom attribute, stereotype:
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Constructor)]
public class Stereotype : System.Attribute
{
public string TheStereotypeName = "General";
public string TheDescription = "Method Info";
public Stereotype()
{
}
public Stereotype(string aStereotype, string aDescription)
{
TheStereotypeName = aStereotype;
Description = aDescription;
}
}
Every class requires two things to make it an attribute.
- An AttributeUsage Attribute to declare the class as an attribute.
- Derive from System.Attribute or some other attribute ultimately derived from System.Attribute.
Below is the attribute usage from our example allowing our attribute to be associated with a class or a method or a constructor of a class:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Constructor)]
This element before the class takes 3 possible parameters.
Parameter |
Description |
Default |
Example |
AttributeTargets |
What element of the class the attribute is targetting |
AttributeTargets.All |
the sample attribute targets classes constructors, and methods (see above) |
IsAttributeMultiUse |
Can the attribute be set multiple times. |
false |
[Conditional("A"),Conditional("B")] |
IsAttributeInherited |
The attribute can be inherited from derived classes. |
false |
|