Using a Custom Attribute - CSharp Custom Type

CSharp examples for Custom Type:Attribute

Description

Using a Custom Attribute

Demo Code

using System;//from   w  w w  .j  a  va2 s  .  co m
[AttributeUsage(AttributeTargets.All)]
public class CodeStatusAttribute : System.Attribute
{
   private string pSTATUS;
   private string pTESTER;
   private string pCODER;
   public CodeStatusAttribute( string Status )
   {
      this.pSTATUS = Status;
   }
   public string Tester
   {
      set
      {
         pTESTER = value;
      }
      get
      {
         return pTESTER;
      }
   }
   public string Coder
   {
      set
      {
         pCODER = value;
      }
      get
      {
         return pCODER;
      }
   }
   public override string ToString()
   {
      return pSTATUS;
   }
}
[CodeStatus("Beta", Coder="A")]
public class Circle
{
   public Circle()
   {
}
}
[CodeStatus("Final", Coder="Fred", Tester="B")]
public class Square
{
public Square()
{
}
}
[CodeStatus("Alpha")]
public class Triangle
{
public Triangle()
{
}
}
[CodeStatus("Final", Coder="C")]
public class Rectangle
{
public Rectangle()
{
}
}
class reflAttr
{
public static void Main()
{
PrintAttributes(typeof(Circle));
PrintAttributes(typeof(Triangle));
PrintAttributes(typeof(Square));
PrintAttributes(typeof(Rectangle));
}
public static void PrintAttributes( Type psdType )
{
Console.WriteLine("\nAttributes for: {0}", psdType.ToString());
Attribute[] attribs = Attribute.GetCustomAttributes(psdType);
foreach (Attribute attr in attribs)
{
CodeStatusAttribute item = (CodeStatusAttribute) attr;
Console.WriteLine("Status is {0}. Coder is {1}. Tester is {2}.",item.ToString(), item.Coder, item.Tester);
}
}
}

Result


Related Tutorials