📜 ⬆️ ⬇️

Attributes in C #

Quite a lot of time before me did not reach what kind of thing these attributes .

I sat down, figured out, read incomprehensible definitions, and suggest that I get an understanding of what it is.

An attribute is a class inherited from the base class Attribute.
The essence of the attribute is that it is used to generate descriptions. Having created an attribute, you can assign it with your own properties that you wish to award a class, field, property or method. The attribute does not affect the value of the fields and properties and the performance of the class methods if the body of the method does not take into account the information stored in the attribute. But there is a very important point - the attribute value cannot be changed during code execution, since the values ​​of their properties are stored as constants in the compiled module

For example, using attributes, you can analyze their values ​​for the type and build various schemes for performing actions on it.
Not very clear, then an example:
')
There is an attribute:

public class MyAttribute : Attribute //        { public int Count { get; set; } //        //           } 


And a certain class which we will award with the described attribute and we will use its value to form the result of the GetArray function:

 [MyAttribute{ Count = 3 }] public class IntArrayInitializer { public int[] GetArray() { var type = this.GetType(); //    if (Attribute.IsDefined(type, typeof(MyAttribute))) //     { var attributeValue = Attribute.GetCustomAttribute(type, typeof(MyAttribute)) as MyAttribute; //    return new int[attributeValue.Count]; //       } return new int[0]; } } 


As can be seen from the code, first we get a description of our class, then we check the presence of our attribute and, if it exists, we create an array with the number of elements specified in the attribute.

And now, inheriting from this class and specifying a new attribute value to another class, when we call the method, we get an array of the desired dimension.

This article gives only a general and meager description of attributes, but using it, you can understand what it is.

Source: https://habr.com/ru/post/172859/


All Articles