#469 – Attaching an Attribute to a Type Member
December 6, 2011 Leave a comment
An attribute describes metadata that should be associated with a particular type member.
Below is an example of attaching the Obsolete attribute to the Cow.FeedCowInBarn method. A developer can use this attribute to mark a method as being obsolete or deprecated, indicating that it should no longer be called.
You attach an attribute to a type member by using a square bracket followed by the name of the attribute and then any arguments that the attribute takes. The Obsolete attribute takes a single argument that will be displayed at compile time when code tries to call the associated method.
[Obsolete("Feeding cows indoors is no longer recommended. Instead, call the LetGrazeOutside() method.")] public void FeedCowInBarn() { Console.WriteLine("Cow eats slop in dim confines of barn"); }
Intellisense now tells us that the method is deprecated.
We also see the specified message at compile-time.