In my previous article I discussed about what are the predefined attributes and how to use predefined attributes. Today we discuss about Custom Attributes in C#. Custom means our own, Custom Attributes means attributes which are not predefined. Custom Attributes are User defined attributes in C#.
We can create the custom attribute by inheriting the System.Attribute class. Lets discuss how to create Custom Attribute with example.
Open Microsoft Visual Studio => Create New Console Project and name it as CustomAttributesCSharp and create our custom attribute DescAttribute by inheriting the Attribute class shown below.
public class DescAttribute : Attribute
{
protected string sHelpText;
public DescAttribute(string HelpText)
{
this.sHelpText = HelpText;
}
public string Desc
{
get
{
return this.sHelpText;
}
}
}
Now use this DescAttribute custom attribute for any class as shown below.
[DescAttribute("This is the Employee class which provides the Employee information")]
class Employee
{
}
In my next articles we will discuss about what are the properties of Custom Attributes we have to consider and advanced Custom Attributes in C#.