Tuesday, July 29, 2008

Can I create my own metadata attributes?

Yes. Simply derive a class from System.Attribute and mark it with the AttributeUsage attribute. For example:
    [AttributeUsage(AttributeTargets.Class)]
    public class InspiredByAttribute : System.Attribute
    {
        public string InspiredBy;
   
        public InspiredByAttribute( string inspiredBy )
        {
            InspiredBy = inspiredBy;
        }
    }


    [InspiredBy("Andy Mc's brilliant .NET FAQ")]
    class CTest
    {
    }


    class CApp
    {
        public static void Main()
        {       
            object[] atts = typeof(CTest).GetCustomAttributes(true);

            foreach( object att in atts )
                if( att is InspiredByAttribute )
                    Console.WriteLine( "Class CTest was inspired by {0}", ((InspiredByAttribute)att).InspiredBy  );
        }
    }

No comments: