Use Reflection to get the Attribute : Attributes Reflection : Attribute C# Examples


C# Examples » Attribute » Attributes Reflection »

 

Use Reflection to get the Attribute









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



Output

Value of MyDescriptionAttribute
-> Info


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Attribute
» Attributes Reflection