#472 – 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.

    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);
        }

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 43 other followers