Justin DuJardin |O_o| |x_X| |-_-| |o_O|

  • Home
28
Mar/10
0

Custom Metadata tags in C# code

Some dynamic languages like C# and ActionScript allow you to put metadata inline with your code.  Metadata can be a really cool way to make extra data available to you at runtime.  To make full use of it, you need to know how to specify this metadata and then how to access it.

MetadataSample.cs

The sample below shows how to specify a custom Attribute called “SomeExtraData”, use it on a class “SomeClass” and retrieve the custom data in code for further use.

using System;
using System.Diagnostics;

namespace SilverShorts
{
   // This class makes the [SomeExtraData] tag below valid
   class SomeExtraData : Attribute
   {
      public string SomeField;
   }

   // Tag this class with a custom attribute
   [SomeExtraData (SomeField="SomeValue")]
   class SomeClass
   {
      public SomeClass()
      {
         // Retrieve the value of the SomeField item in the metadata
         // tag on this class.
         Type t = typeof(SomeClass);
         SomeExtraData attr = t.GetCustomAttributes(false)[0] as SomeExtraData;
         Debug.WriteLine("SomeExtraData.SomeField = " + attr.SomeField);
      }
   }
}

A word of caution: Be aware of how often you perform operations like querying custom attributes in the constructor above.  The system reflection calls can negatively impact performance if you abuse them. I won’t preach about it, just use them only when you need to.

Tagged as: Attribute, C#, Metadata
No Comments

Recent Posts

  • Getting Back To My Roots
  • Implicit Types (var) in C#
  • Canvas Element Positioning Performance

Archives

  • June 2010 (2)
  • May 2010 (1)
  • March 2010 (3)
  • February 2010 (1)
  • November 2009 (3)
  • September 2009 (3)
  • August 2009 (1)
  • June 2009 (2)

Twitter

Justin DuJardin
  • Sometimes you need to follow the carrot right over the edge of a cliff, just to see what happens. Gravity isn't so tough. August 28, 2010 from MetroTwit
  • RT @StuMcDnld: Unaddressed assumptions will absolutely ruin relationships. Honest communication is imperative in ALL areas of life. August 21, 2010 from MetroTwit
Copyright © 2010 Justin DuJardin · Powered by Wordpress and developed by Andrei Luca for you.