Attributes
The ability to reflect methods and type information is a nice and intriguing technology, but reflection really shines and demonstrates its value when you use it in conjunction with .NET attributes. The idea behind attributes is simple: instead of coding functionality and features into your objects, you can add them by decorating your objects with attributes. The information in the attributes is added to the metadata about the objects that the compiler generates (its methods, base classes, etc.). .NET (or your custom tools) can read the metadata, look for the attributes, and then perform the functionality and add the features the attributes specify without the object’s or its developer’s involvement. For example, when you want to combine enums in a binary masking value, you can use the Flags attribute:
[Flags]
public enum WeekDay
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday,
}When the compiler sees the Flags attribute, it allows you to combine enum values with the | (OR) operator, as if they were integer powers of 2. For example:
const WeekDay Weekend = WeekDay.Saturday|WeekDay.Sunday;Another example is the Conditional attribute, defined in the System.Diagnostics namespace. This attribute directs the compiler to exclude from a build calls to any method it decorates if a specified condition isn’t defined:
#define MySpecialCondition //usually DEBUG
public class MyClass
{
public MyClass()
{}
[Conditional("MySpecialCondition")] public void MyMethod() {...} ...