Retrieve Attribute by using reflection : Attributes Reflection : Attribute C# Examples


C# Examples » Attribute » Attributes Reflection »

 

Retrieve Attribute by using reflection









    
using  System;    
using  System.Reflection;  
    
[AttributeUsage(AttributeTargets.All)]  
public  class  MyAttribute  :  Attribute  {  
    public  string  remark;  
  
    public  MyAttribute(string  comment)  {  
        remark  =  comment;  
    }  
  
    public  string  Remark  {  
        get  {  
            return  remark;  
        }  
    }  
}    
  
[MyAttribute("This  class  uses  an  attribute.")]  
class  UseAttrib  {  
}  
  
class  MainClass  {    
    public  static  void  Main()  {    
        Type  t  =  typeof(UseAttrib);  
  
        Console.Write("Attributes  in  "  +  t.Name  +  ":  ");  
  
        object[]  attribs  =  t.GetCustomAttributes(false);    
        foreach(object  o  in  attribs)  {  
            Console.WriteLine(o);  
        }  
  
        Console.Write("Remark:  ");  
  
        //  Retrieve  the  MyAttribute.  
        Type  tRemAtt  =  typeof(MyAttribute);  
        MyAttribute  ra  =  (MyAttribute)  
                    Attribute.GetCustomAttribute(t,  tRemAtt);  
  
        Console.WriteLine(ra.remark);  
    }    
}
    
   
  
   



Output

Attributes in UseAttrib: MyAttribute
Remark: This class uses an attribute.


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Attribute
» Attributes Reflection