Mega Code Archive

 
Categories / C# / Reflection
 

Use GetCustomAttributes from Type to get custom attributes

using System; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)] public class AuthorAttribute : System.Attribute {     private string company; // Creator's company     private string name;    // Creator's name     public AuthorAttribute(string name)     {         this.name = name;         company = "";     }     public string Company     {         get { return company; }         set { company = value; }     }     public string Name     {         get { return name; }     } } [assembly: Author("Allen", Company = "Ltd.")] [Author("Allen", Company = "Objective Ltd.")] class SomeClass { } [Author("Lena")] public class SomeOtherClass { } [Author("FirstName")] [Author("Allen", Company = "Ltd.")] class MainClass {     public static void Main()     {         Type type = typeof(MainClass);         object[] attrs = type.GetCustomAttributes(typeof(AuthorAttribute), true);         foreach (AuthorAttribute a in attrs)         {             Console.WriteLine(a.Name + ", " + a.Company);         }     } }