In this article, we will see together how to create our own 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 attributes

Let’s first create our own attribute:

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

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:

Happy coding!  🙂