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.