Defining New Attribute Classes : Attribute : Language Basics C# Source Code


Custom Search

C# Source Code » Language Basics » Attribute »

 

Defining New Attribute Classes








    
 


using System;
using System.Diagnostics;
using System.Reflection;
   
[AttributeUsage(AttributeTargets.Class)]
public class ClassAuthorAttribute : Attribute
{
    private string AuthorName;
   
    public ClassAuthorAttribute(string AuthorName)
    {
        this.AuthorName = AuthorName;
    }
   
    public string Author
    {
        get
        {
            return AuthorName;
        }
    }
}
   
[ClassAuthor("AA")]
public class TestClass
{
    public void Method1()
    {
        Console.WriteLine("Hello from Method1!");
    }
   
    [Conditional("DEBUG")]
    public void Method2()
    {
        Console.WriteLine("Hello from Method2!");
    }
   
    public void Method3()
    {
        Console.WriteLine("Hello from Method3!");
    }
   
}
   
public class MainClass
{
    public static void Main()
    {
        TestClass MyTestClass = new TestClass();
   
        MyTestClass.Method1();
        MyTestClass.Method2();
        MyTestClass.Method3();
   
        object []  ClassAttributes;
        MemberInfo TypeInformation;
   
        TypeInformation = typeof(TestClass);
        ClassAttributes = TypeInformation.GetCustomAttributes(typeof(ClassAuthorAttribute), false);
        if(ClassAttributes.GetLength(0) != 0)
        {
            ClassAuthorAttribute ClassAttribute;
   
            ClassAttribute = (ClassAuthorAttribute)(ClassAttributes[0]);
            Console.WriteLine("Class Author: {0}", ClassAttribute.Author);
        }
    }
}

 
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo Language Basics
» Attribute