How to work with attributes in C#

An attribute is a declarative tag that is used to convey information to runtime about the behaviors of various elements like classes, methods, structures, enumerators, assemblies etc. in your program. You can add declarative information to a program by using an attribute. A declarative tag is depicted by square ([ ]) brackets placed above the element it is used for.

The following is the syntax of an attribute −

[attribute(positional_parameters, name_parameter = value, ...)]

The .Net Framework provides two types of attributes: the pre-defined attributes and custom built attributes.

Let us see how to declare a custom attribute −

//a custom attribute BugFix to be assigned to a class and its members
AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AllowMultiple = true)]
public class DeBugInfo : System.Attribute