How to work with attributes in C#

CsharpProgrammingServer Side Programming

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, ...)]
Element

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
[AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]
public class DeBugInfo : System.Attribute
raja
Updated on 22-Jun-2020 11:00:52

Advertisements