Attributes Can Be Attached to a Variety of Elements

Custom attributes can be attached not only to class methods, but to a number of different types of elements.
You can attach an attribute to any of the following elements:
  • An assembly
  • A class
  • A constructor
  • A delegate
  • An enumerated type
  • An event
  • A field
  • A generic parameter
  • An interface
  • A method
  • A module (.dll or .exe)
  • A parameter
  • A property
  • A return value
  • A struct
Below is an example of attaching custom attributes to parameters.
1
2
3
4
5
6
7
8
9
10
11
public sealed class PopCultureAttribute : Attribute
{
    public string Trivia;
    public object SuggestedValue;
 
    public PopCultureAttribute(string trivia, object suggestedValue)
    {
        Trivia = trivia;
        SuggestedValue = suggestedValue;
    }
}



1
2
3
4
5
6
public void FeedCowInBarn(
    [PopCulture("Cows stomachs can bloat when feeding them rich grains", "Silage")] string feedType,
    [PopCulture("Cows spend 6 hrs/day eating", 60)] int numMinutes)
{
    Console.WriteLine("Cow eats slop in dim confines of barn.  {0}, {1}", feedType, numMinutes);
}