#472 – Attributes Can Be Attached to a Variety of Elements
December 9, 2011 2 Comments
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.
public sealed class PopCultureAttribute : Attribute { public string Trivia; public object SuggestedValue; public PopCultureAttribute(string trivia, object suggestedValue) { Trivia = trivia; SuggestedValue = suggestedValue; } }
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); }