Creating Custom Attribute in C# with Example
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 System; namespace Hello_World { public sealed class MyName:System.Attribute { public string info { get; set; } public MyName(string _info) { info = _info; } public MyName() { } } }
Using Constructor:
using System; namespace Hello_World { class Program { static void Main(string[] args) { FullName("Peter", "Todd"); } //MyName Attribute with message as parameter. [MyName( "This is method returns fullname. ")] public static void FullName(string first, string last) { Console.WriteLine("Full Name: {0} {1}", first, last ); } } }
Without Using Constructor:
using System; namespace Hello_World { class Program { static void Main(string[] args) { FullName("Peter", "Todd"); } //MyName Attribute with message as parameter. [MyName( info="This is method returns fullname. ")] public static void FullName(string first, string last) { Console.WriteLine("Full Name: {0} {1}", first, last ); } } }