Defining New Attribute Classes : Attribute « Language Basics « C# / C Sharp






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

 








Related examples in the same category

1.Subclass System.Attribute
2.A simple attribute exampleA simple attribute example
3.Use a named attribute parameterUse a named attribute parameter
4.Creating and using a class attribute.
5.Attribute in class inheritance
6.Use AttributeUsage
7.Use a property as a named attribute parameterUse a property as a named attribute parameter
8.Demonstrate the Conditional attributeDemonstrate the Conditional attribute
9.Define contant and use it in Conditional attribute
10.Demonstrate the Obsolete attributeDemonstrate the Obsolete attribute
11.Illustrates use of the Obsolete attribute
12.Compiles into a library defining the RamdomSupplier attribute and the RandomMethod attribute
13.Shows the use of assembly attributes
14.How to create a custom attributeHow to create a custom attribute
15.Illustrates use of the Conditional attributeIllustrates use of the Conditional attribute
16.Illustrates the GetCustomAttributes methodIllustrates the GetCustomAttributes method
17.demonstrates the flags attribute of an enumeration