Home »

Can I create my own metadata attributes?

Question ListCategory: ASP.NETCan I create my own metadata attributes?
jeanderson295 author asked 8 years ago
1 Answers
shah_kajal184 author answered 8 years ago

Yes. Simply derive a class from System.Attribute and mark it with theAttributeUsage 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 );
}
}

Please login or Register to Submit Answer