Code Reference A collection of code for my reference (and perhaps other people too)

15Mar/100

Custom Attributes

If you would like to adorn your classes with some custom meta-data, Custom Attributes are the way to go.

First, start with your class.

public class MyDumbClass
{
    public MyDumbClass()
    {
        // do nothing
    }
}

Now we want to say some things about this class... like, is it a good class?
We create an attribute where we can specify this info.
Create a class that inherits from 'Attribute'.
Add some fields to the class.

public class MySpecialAttribute : Attribute
{
    public string GoodAdvice { get; set; }
    public bool ThisClassIsGood { get; set; }
}

Now you can find in your intellesense the "MySpecial" attribute.

[MySpecial(ThisClassIsGood = true, GoodAdvice="Do no harm")]
public class MyDumbClass
{
    public MyDumbClass()
    {
        // do nothing
    }
}

The attribute name, as you can see, is the name of the attribute class without the 'Attribute' text.

Because there can never be to much good in the world, you may wish to add the attribute several times.
Doing so will give you an error unless you specify the attribute can be used multiple times.

On the Attribute class, add an AttributeUsage attribute:

[AttributeUsage(AttributeTargets.Class, AllowMultiple=true)]
public class MySpecialAttribute : Attribute
{
    public string GoodAdvice { get; set; }
    public bool ThisClassIsGood { get; set; }
}

We chose 'AttributeTarget.Class' because we are using it on a class. If you want the attribute used on a field, or method or something else, you can specify AttributeTargets.Method or whatever you need.