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

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.

2 Responses to #472 – Attributes Can Be Attached to a Variety of Elements

  1. I’ve only ever seen this done for COM interop using [In] and [Out] attributes. In what other situations would you attach attributes to a parameter? How do parameters benefit from having attributes added to them?

    • Sean says:

      I can’t think of a perfect example right now, but it seems like it would be useful to embed the attribute data because you could then pull it out using reflection–either at runtime, or as something that a tool uses. (e.g. Visual Studio plug-in).

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: