Attribute in C #

The attribute in C #, is a declaration tag, used to transmit information to the runtime about the behavior of various elements such as classes, methods, structures, enum, assemblies, etc. in the program. yours. You can add declaration information to the program using the attribute. A declaration tag is described by square brackets ([]) placed above the element to which it is used.

Attributes are used to add metadata, such as compilation instructions and other information such as comments, descriptions, methods and classes to a program. .Net Framework provides two types of attributes: pre-defined attribute and custom attribute (custom built attribute).

Define an Attribute in C #

The syntax for defining an Attribute in C # is as follows:

 [ attribute ( positional_parameter , name_parameter = gi á _tr ị, .)] element 

The name of the attribute and its value are defined inside the square brackets, before the element that the attribute is applied to positional_parameter specifying essential information and name_parameter specifying the optional information.

Predefined predefined in C #

.Net Framework provides 3 Attributes defined in advance:

  1. AttributeUsage
  2. Conditional
  3. Obsolete

AttributeUsage in C #

AttributeUsage describes how a custom attribute class can be used. It determines the type of items, from which attributes can be applied to.

The syntax for determining this attribute in C # is as follows:

 [ AttributeUsage ( validon , AllowMultiple = allowmultiple , Inherited = inherited )] 

Inside:

  1. validon : defines language elements that attributes can be set. It is the combination of the value of an AttributeTargets enumerator. The default value is AttributeTargets.All .
  2. allowmultiple (optional): provide value for AllowMultiple feature of this attribute, a Boolean value. If this is true, the attribute is multiuse. The default value is false (ie single-use - only once).
  3. inherited (optional): provides value for the Inherited property of this attribute, a Boolean value. If it is true, the attribute is inherited by derived classes. The default value is false (not inherited).

For example:

 [ AttributeUsage ( AttributeTargets . Class | AttributeTargets . Constructor | AttributeTargets . Field | AttributeTargets . Method | AttributeTargets . Property , AllowMultiple = true )] 

Conditional in C #

Attribute Conditional marks a conditional method whose execution depends on a designated preprocessor identifier.

It causes conditional compilation of method calls, depending on the given value, such as Debug or Trace . For example, it displays the value of variables while debugging a code.

The syntax for determining this attribute in C # is as follows:

 [ Conditional ( conditionalSymbol )] 

For example:

 [ Conditional ( "DEBUG" )] 

Here is an example of Conditional illustration in C #:

 #define DEBUG using System ; using System . Diagnostics ; public class QuanTriMangCom { [ Conditional ( "DEBUG" )] public static void Message ( string msg ) { Console . WriteLine ( msg ); } } class Test { static void function1 () { QuanTriMangCom . Message ( "Trong hàm 1." ); function2 (); } static void function2 () { QuanTriMangCom . Message ( "Trong hàm 2." ); } public static void Main () { QuanTriMangCom . Message ( "Trong hàm Main." ); function1 (); Console . ReadKey (); } } 

Use the Console.ReadKey command (); to see the results more clearly.

Compiling and running the above C # program will produce the following results:

 In the Main function 
In function 1.
In function 2.

Obsolete in C #

In C #, Obsolote marks a program entity that should not be used. It tells you to tell the compiler to remove a specific target element. For example, when a new method is being used in a class and if you still want to retain the old method in this class, you can mark it as obsolete (obsolete) by displaying a message as method. New mode will be used, instead of the old one.

The syntax to define this attribute in C # is as follows:

 [ Obsolete ( message )] [ Obsolete ( message , iserror )] 

Inside:

The message is a string describing why the item is obsolete and what is used instead.

iserror is a Boolean value. If its value is true, the compiler will treat the use of this item as an error. The default value is false (ie the compiler will generate a warning).

The following example illustrates obsolete in C #:

 using System ; public class QuanTriMangCom { [ Obsolete ( "Đừng sử dụng QTM1, hãy sử dụng QTM2" , true )] static void QTM1 () { Console . WriteLine ( "Đây là phương thức cũ" ); } static void QTM2 () { Console . WriteLine ( "Đây là phương thức mới" ); } public static void Main () { QTM1 (); } } 

When you try to compile the above program, the compiler will issue an error message:

Compilation failed: 1 error(s), 0 warnings
main.cs(13,7): error CS0619: `QuanTriMangCom.QTM1()' is obsolete: `Đừng sử dụng QTM1, hãy sử dụng QTM2'

Create Custom Attribute in C #

Also called custom attributes or user-defined attributes. The .Net Framework allows creating Custom Attributes that can be used to store declaration information and can be retrieved at runtime. This information may relate to any target element depending on the design criteria and application requirements.

Creating and using Custom Attribute in C # includes 4 steps:

  1. Declare a Custom Attribute
  2. Build Custom Attribute
  3. Apply Custom Attribute on a target program element
  4. Accessing Attributes through Reflection

The final step involves writing a simple program to read through metadata to find different notations. Metadata is data or information used to describe other data. This program should use reflection to access attributes at runtime. We will talk more about this in the next article.

Step 1: Declare a Custom Attribute in C #

A new Custom Attribute should be derived from the System.Attribute class in C #. For example:

 //Thuộc tính tùy chính BugFix được gán cho lớp và thành viên của nó. [ AttributeUsage (
AttributeTargets . Class | AttributeTargets . Constructor | AttributeTargets . Field | AttributeTargets . Method | AttributeTargets . Property , AllowMultiple = true )] public class DeBugInfo : System . Attribute

In the above code, we have declared a Custom Attribute as DeBugInfo.

Step 2: Build Custom Attribute in C #

We build a Custom Attribute named DeBugInfo, which stores the information obtained by debugging any program. It will store the following information:

  1. Code of error
  2. The name of the developer has identified the error
  3. Last review of that code
  4. A string message to store developer comments

The DeBugInfo class has 3 private properties to store the first 3 information and a public property to store the message. Therefore, the error code, developer name, and review date are the corresponding positional_parameter of DeBugInfo class and notice the name_parameter.

Each attribute must have at least one constructor. The corresponding positional_parameter should be transmitted through that constructor. The following example illustrates the DeBugInfo class on:

 //Custom attribute BugFix được gán cho các lớp và thành viên của nó.
 [ AttributeUsage ( AttributeTargets . Class | AttributeTargets . Constructor | AttributeTargets . Field | AttributeTargets . Method | AttributeTargets . Property , AllowMultiple = true )] public class DeBugInfo : System . Attribute { private int bugNo ; private string developer ; private string lastReview ; public string message ; public DeBugInfo ( int bg , string dev , string d ) { this . bugNo = bg ; this . developer = dev ; this . lastReview = d ; } public int BugNo { get { return bugNo ; } } public string Developer { get { return developer ; } } public string LastReview { get { return lastReview ; } } public string Message { get { return message ; } set { message = value ; } } } 

Step 3: Apply Custom Attribute in C #

The Custom Attribute in C # is applied by placing it right before its target:

 [ DeBugInfo ( 45 , "Nguyễn Huy" , "03/09/2017" , Message = "Kiểu trả về không hợp lệ" )] [ DeBugInfo ( 49 , "Hà Minh" , "09/11/2017" , Message = "Biến chưa được sử dụng" )] class Rectangle { //các biến thành viên protected double dai ; protected double rong ; public Rectangle ( double d , double r ) { dai = d ; rong = r ; } [ DeBugInfo ( 55 , "Nguyễn Huy" , "03/09/2017" , Message = "Kiểu trả về không hợp lệ" ) ] public double tinhS () { return dai * rong ; } [ DeBugInfo ( 56 , "Hà Minh" , "09/11/2017" ) ] public void Display () { Console . WriteLine ( "Chiều dài: {0}" , dai ); Console . WriteLine ( "Chiều rộng: {0}" , rong ); Console . WriteLine ( "Diện tích: {0}" , tinhS ()); } } 

In the next chapter, we retrieve information Attribute using a Reflection class object in C #.

Follow tutorialspoint

Previous article: File I / O in C #

Next article: Reflection in C #

4 ★ | 1 Vote

May be interested

  • How to Remove 'Read Only' Attribute on MS Word FilesHow to Remove 'Read Only' Attribute on MS Word Files
    this article shows you how to remove 'read only' mode, which does not allow editing on microsoft word documents. although you cannot remove the read-only mode of a secured word document without knowing the password, you can easily copy the word document content into a new word file.
  • SEQUENCE in SQL ServerSEQUENCE in SQL Server
    sequence is often used in databases because it is necessary for many applications. the article will provide syntax and examples of how to create and delete the sequence and its attributes in sql server.
  • HTML color code - color code table in htmlHTML color code - color code table in html
    the color displayed is a combination of 3 colors red, green and blue. below is a table of color codes in html and how to use color codes in html
  • The vars () function in PythonThe vars () function in Python
    the vars () function in python returns the __dict__ attribute of the passed object if the object has the __dict__ attribute.
  • Properties of .NETProperties of .NET
    attribute is one of the most important concepts of .net, it affects many different aspects of a .net application such as the ability to communicate with com components, the ability to create a service, calculate security features, feature to save the object's data to file ...
  • Image Map in JavaScriptImage Map in JavaScript
    you can use javascript to create image map at client-side. image maps are activated by the usemap attribute for the tag and are defined by special extension tags and.
  • Build Dan Heng Honkai Star Rail to the latest standardBuild Dan Heng Honkai Star Rail to the latest standard
    honkai star rail 1.3 has officially launched dan heng, this 5-star character has the destiny of destruction and the imaginary number attribute, so dan heng's role in the team has been shaped as a key dps.
  • Property (Property) in C #Property (Property) in C #
    properties - property is the member named for the layer, structure, and interface. member variables or methods in a class or structure are called fields. attribute is an inheritance of fields and is accessed using the same syntax. they use accessor through the values ​​of private fields that can be read, written, and manipulated.
  • Border Image - Create image borders in CSSBorder Image - Create image borders in CSS
    css border image is adding images that appear on the border for elements.
  • Opacity / Transparency property in CSSOpacity / Transparency property in CSS
    the opacity attribute determines the opacity and transparency of an element.