Creating a custom attribute in .NET

Attributes are used throughout the .NET Framework. Creating and using your own attributes is very simple, though there doesn’t seem to be many basic examples out there demonstrating how this is done. So I’ve put together the following article which demonstrates how to create and use a custom attribute. While it is very simplified and wouldn’t be much use in the real world, it will serve as a demonstration and help you to understand how this is done.

First of all we will create the attribute class. Create a class derived from System.Attribute and add a couple of fields. It is best practice to add the “Attribute” suffix to the end of the name. This does not need to be included when decorating a type or type member with the attribute as you’ll see.

public class DemoAttribute : System.Attribute
{
    public string Name = "";
    public string Country = "";
}

 
With the attribute class created, lets create another class to demonstrate how to use the attribute. Note I’ve excluded the “Attribute” suffix, this is accepted by .NET and makes code more easily readable.

[Demo(Name="Arthur" ,Country="UK")]
public class Consumer

 
Finally lets read the attribute through the constructor and dump the results to the console window. The following section shows the complete code for the class we’re consuming our DemoAttribute with.

[Demo(Name="Arthur", Country="UK")]
public class Consumer
{
    public Consumer()
    {
        Demo[] theseAtts = (Demo[])this.GetType()
            .GetCustomAttributes(typeof(Demo),
            true); //Inherit?

        Console.WriteLine(theseAtts[0].Name +
          theseAtts[0].Country);
    }
}

Run the following code to test:

static void Main(string[] args)
{
    Consumer c = new Consumer();
}

Output should be:

Arthur UK

As I said, not a real-world example, but you should be able to get the jist of how attributes work.

Tags: , ,