Creating Custom Attribute in C# with Example

Rating: 5 - 1 Votes

Creating Custom Attribute in C# with Example

C#This time, we are going to create a custom attribute class.  We have seen in previous tutorial how Obsolete attribute works.  We are going to replicate a bit of similar functionality in our custom attribute class.

First of all, we will create a class called MyName which will inherit from System.Attribute class.  This custom attribute class will be of sealed type to avoid inheritance.  We will have property called info.  We will create a custom constructor, which will take a string as parameter and assign it to the property info.  You can also assign value directly to the property info without using custom constructor in the main class.  Example of both scenarios is given below.

Since attributes provide declarative information, this information can be obtained using reflection or any other external DotNet tool like Ildasm.

Custom Attribute Class:

Using Constructor:

Without Using Constructor: