Logo 
Search:

.Net Framework FAQ

Submit Interview FAQ
Home » Interview FAQ » .Net FrameworkRSS Feeds

Can I create my own metadata attributes?

  Shared By: Devlan Jones    Date: Feb 10    Category: .Net Framework    Views: 1790

Answer:

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

Share: 
 

Didn't find what you were looking for? Find more on Can I create my own metadata attributes? Or get search suggestion and latest updates.


Your Comment
  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].


Tagged: