Click here to Skip to main content
15,867,985 members
Articles / Programming Languages / C#
Article

Writing custom attributes in C#

Rate me:
Please Sign up or sign in to vote.
2.75/5 (9 votes)
2 Nov 2006CPOL1 min read 34.2K   347   17   1
This article and sample tries to describe how to implement custom attributes using C#.

Introduction

This small sample tries to show how to write custom attributes in C#. This sample makes no sense, but demonstrates the implementation of custom attributes in a simple way.

Description

Attributes are implemented in classes which have to inherit from Attribute. Further on, you have to put the AttributeUsageAttribute in front of your class. The AttributeUsageAttribute describes on which targets your attribute can be applied to. These are the valid targets:

ModuleAttribute can be applied to a module
AllAttribute can be applied to any application element
AssemblyAttribute can be applied to an assembly
ClassAttribute can be applied to a class
ConstructorAttribute can be applied to a constructor
DelegateAttribute can be applied to a delegate
EnumAttribute can be applied to an enumeration
EventAttribute can be applied to an event
FieldAttribute can be applied to a field
GenericParameterAttribute can be applied to a generic parameter
InterfaceAttribute can be applied to an interface
MethodAttribute can be applied to a method

In addition, you can also add some named properties:

  • AllowMultiple - Gets or sets a boolean value indicating whether more than one instance of the indicated attribute can be specified for a single program element.
  • Inherited - Gets or sets a boolean value indicating whether the indicated attribute can be inherited by derived classes and overriding members.

In this caseb our attribute can be applied on classes:

C#
[AttributeUsage(AttributeTargets.Class)]
public class MyCustomAttribute : Attribute
{
    private string attributevalue;
    
    public MyCustomAttribute(string AttributeValue)
    {
        attributevalue = AttributeValue;
    }
    public string AttributeValue
    {
        get
        {
            return attributevalue;
        }
    }
}

For an easy access on the value of our new attribute, we need to implement a second class from which classes can be inherited:

C#
public class MyCustom
{
    public string AttributeValue
    {
        get
        {
            string Value = null; 
            Type type = this.GetType();
            MyCustomAttribute[] attribs = (MyCustomAttribute[])
              type.GetCustomAttributes(typeof(MyCustomAttribute), true);
            if (attribs.Length > 0)
            {
                MyCustomAttribute attrib = attribs[0];
                Value = attrib.AttributeValue;
            }
            return Value;
        }
    }
}

The last step is to test the new attribute:

C#
[MyCustom("Test")]
class TestClass : MyCustom
{
}

class Program
{
    static void Main(string[] args)
    {
        ///Create a instance of our class
        TestClass test = new TestClass();
        ///Write the value of the Property to the
        ///console
        Console.WriteLine("The value of the attribute is: " + 
                          test.AttributeValue);
        Console.WriteLine("Press any key...");
        Console.ReadKey(false);
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Systems Engineer
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralPrepare your code Pin
Sceptic Mole5-Nov-06 2:58
Sceptic Mole5-Nov-06 2:58 
Download a template ASP file here, and read template instructions[^]

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.