Click here to Skip to main content
11,490,973 members (63,581 online)
Click here to Skip to main content

Writing custom attributes in C#

, 2 Nov 2006 CPOL 22.8K 305 16
Rate this:
Please Sign up or sign in to vote.
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:

Module Attribute can be applied to a module
All Attribute can be applied to any application element
Assembly Attribute can be applied to an assembly
Class Attribute can be applied to a class
Constructor Attribute can be applied to a constructor
Delegate Attribute can be applied to a delegate
Enum Attribute can be applied to an enumeration
Event Attribute can be applied to an event
Field Attribute can be applied to a field
GenericParameter Attribute can be applied to a generic parameter
Interface Attribute can be applied to an interface
Method Attribute 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:

[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:

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:

[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)

Share

About the Author

datenkabel
Systems Engineer
Germany Germany
No Biography provided

Comments and Discussions

 
GeneralPrepare your code Pin
Sceptic Mole5-Nov-06 3:58
memberSceptic Mole5-Nov-06 3:58 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150520.1 | Last Updated 2 Nov 2006
Article Copyright 2006 by datenkabel
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid