In this article, we will see together how to create our own custom attribute with C#, and then get the value of it thanks to reflection through a simple example.

What is an Attribute?

An attribute is basically a metadata object used to provide declarative information to a class, property, enum, … You can retrieve such information at runtime by using reflection. When creating a custom attribute, you will always have to derive from the System.Attribute class.

A simple example using custom attributes

Let’s first create our own attribute:

public class StatusAttribute : Attribute
    public int Priority { get; set; }
Code language: C# (cs)

Now we can use this attribute to define more information on an Enum:

public enum StatusEnum
    [Status(Priority = 99), Description("Not defined")]
    None = 0,

    [Status(Priority = 2), Description("Ready to start")]
    Ready = 1,

    [Status(Priority = 3), Description("The stuff is running")]
    Running = 2,

    [Status(Priority = 4), Description("Execution has been completed")]
    Finnished = 3,

    [Status(Priority = 1), Description("Under initialization")]
    Initializing = 4,

    [Status(Priority = 99), Description("This stuff has all the status at the same time??")]
    All = 99
Code language: C# (cs)

As you can see, we added 2 metadata descriptions. The first one is the one we’ve created just above. You will observe that the StatusAttribute class can be shorten to “Status”. The second attribute is an existing one from .Net (DescriptionAttribute shorten to “Description”).

Now, let’s read this information by reflection:

public static class Program
    static void Main(string[] args)
        var status = StatusEnum.Running;
        var statusPriorityFromAttribute = status.GetAttributeOfType<StatusAttribute>().Priority; //Custom attribute
        var statusDescriptionFromAttribute = status.GetAttributeOfType<DescriptionAttribute>().Description; 

    public static T GetAttributeOfType<T>(this Enum enumVal) where T : Attribute
        var type = enumVal.GetType();
        var memInfo = type.GetMember(enumVal.ToString());
        var attributes = memInfo[0].GetCustomAttributes(typeof(T), false);
        return (attributes.Length > 0) ? (T)attributes[0] : null;
Code language: C# (cs)

For more detail about custom attributes, please have a look at this link. For more info about how to test it with Moq, please look at this article.

Happy coding!  🙂