Click here to Skip to main content
13,050,904 members (62,997 online)
Click here to Skip to main content
Add your own
alternative version

Stats

26.5K views
17 bookmarked
Posted 2 Nov 2006

Writing custom attributes in C#

, 2 Nov 2006
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:

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:

[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

You may also be interested in...

Comments and Discussions

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

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170713.1 | Last Updated 2 Nov 2006
Article Copyright 2006 by datenkabel
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid