Use Reflection to get the Attribute : Attributes Reflection « Attribute « C# / CSharp Tutorial






using System;

[assembly:System.CLSCompliantAttribute(true)]

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]

public class MyDescriptionAttribute : System.Attribute
{
  private string description;
  public string Desc
  {
    get { return description; }
    set { description = value; }
  }

  public MyDescriptionAttribute() {}
  public MyDescriptionAttribute(string desc) 
  { description = desc;}
}


[MyDescriptionAttribute("Info")]
public class MyClass
{
    public MyClass()
    {
    }
}


public class MainClass
{
  public static int Main(string[] args)
  {

    Type t = typeof(MyClass);
  
    // Get all attributes in the assembly.
    object[] customAtts = t.GetCustomAttributes(false);
  
    // List all info.
    Console.WriteLine("Value of MyDescriptionAttribute");
    foreach(MyDescriptionAttribute v in customAtts)
      Console.WriteLine("-> {0}\n", v.Desc);  

    return 0;
  }
}
Value of MyDescriptionAttribute
-> Info








10.5.Attributes Reflection
10.5.1.Reflecting on Attributes
10.5.2.Retrieve Attribute by using reflection
10.5.3.Use Reflection to get the Attribute
10.5.4.Use the GetCustomAttributes method
10.5.5.Load class method by Attribute