What are these attributes in the properties?

9

What are the names of these "Attributes" and what are they used for?

Examples:

in a class declaration:

[ComVisibleAttribute(true)]
public sealed class SerializableAttribute : Attribute

in a property declaration:

[XmlElement]
public string Valor
{
   get { return _valor; }
   set { _valor = value; }
}
    
asked by anonymous 23.12.2014 / 10:55

3 answers

6

You have already seen in the other answers what an attribute is.

They can be used in:

  • Assembly,
  • Module,
  • Class,
  • Struct,
  • Enum,
  • Builder,
  • Method,
  • Property,
  • Field,
  • Event,
  • Interface,
  • Parameter,
  • Delegate,

An example of use in parameters.

void metodo([nonnull] string texto)

Using assembly :

[assembly: Help("this a do-nothing assembly")]

Note that you can explicitly identify where the attribute will be used. In some cases it is the only way to determine the correct scope. See the possible identifiers:

  • assembly
  • module
  • type
  • method
  • property
  • event
  • field
  • param
  • return

They are used to add metadata to the code. Something that the compiler already does in several opportunities according to the use of the language. This feature allows the language user (the programmer) to add their own attributes. You can use attributes created by third parties, including by .Net itself and other Microsoft libraries or not, or use attributes that you have created.

Some of these attributes are used through reflection by libraries and more commonly by frameworks . It can be used by the compiler to change its behavior in relation to something. Or it can be used by external tools like IDEs to take advantage of this, especially in code generators, which help interoperability.

There is a lot of misuse of these attributes even by Microsoft itself in some respects. "Listen to the master .

Different syntax

See this example

[ComVisibleAttribute(true)]

It determines that a member can be accessed directly by a COM object.

But it is not so common to write like this, The most common is this:

[ComVisible(true)]

But how? I went there on the documentation and vi that his name is ComVisibleAttribute . The compiler uses a trick there.

To define a new attribute you must create a class derived from Attribute and by convention the name should end with the word Attribute to avoid conflicts. But to use the compiler more simply when you use the attribute somewhere in the code the compiler looks for it with the name used or with the suffix Attribute .

The class itself that creates an attribute can have specific attributes. It is common to use AttributeUSage , ValidOn , AllowMultiple , Inherited

Other examples:

[XmlElement]

It is used to indicate to XMLSerializer that that member is a member to be considered as XML. So it's an attribute created by. Net to assist one of your classes.

[Browsable(false)]

Determines whether or not the member will be visible in the IDE Properties window.

[DebuggerDisplay("{value}", Name = "{key}")]

How to show that member when inspecting values in debugger .

[Flags]

Make an enumeration a bitfield , that is, each member will have the value evolving geometrically at the ratio of 2 to then be used with operator | and "add" elements.

[Conditional("DEBUG")]

Determines which type of release that code should be run in.

[Serializable]

Determines that the member can be serialized. Commonly used in conjunction with [NonSerializable] .

[Optional]

Used primarily by the compiler to indicate the value that a parameter should take if it is not passed. So it can even be used by languages that do not have this concept. Used in conjunction with [DefaultParameterValue("texto")] .

[Test]

Indicates that the method is a unit test. This tool needs to know what to do.

[assembly: InternalsVisibleTo("ClasseX")]

It does the same as the Friend attribute of C ++.

Full list created on .Net .

A example of what not to do (see the bottom of the page.) This added information should not be code and mainly star available in the executable.

Parameters for attributes

You can not use any information as a parameter of an attribute (which are members of the class that defines the attribute). It needs to be a type that can be solved at compile time. You can use:

  • bool,
  • byte,
  • char,
  • double,
  • float,
  • int,
  • long,
  • short,
  • string
  • System.Type
  • object
  • enum (with constraints)
  • array (with constraints)

Example usage:

using System;
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute {
   public readonly string text;

   public HelpAttribute(string text) {
      this.text = url;
   }
}
[HelpAttribute("http://site/MyClassInfo")]
class MyClass {
    [Help("Método inútil")]
    public void MyMethod() {}

    [Help("Meu inteiro")]
    public int MyInt;
}
class App {
    public static void Main() {
        var assembly = Process.GetCurrentProcess().ProcessName + ".exe";
        foreach (Attribute attr in Assembly.LoadFrom(assembly).GetCustomAttributes(true)) {
            var help = attr as HelpAttribute;
            if (help != null) {
                Console.WriteLine("Descrição de {0}:\n{1}", assembly, help.Description);
            }
        }
    }
}
    
23.12.2014 / 15:16
6

This is the correct name. Attributes , or in English, Attributes .

Attributes have several functions:

  • Define information about the class, property, or method that will be used at runtime;
  • Add functional behaviors to class, property, or method;
  • Define groupings or segregations.

Here is an introduction to Attributes .

    
23.12.2014 / 12:03
2
[Obsolete("Não utilizar esse método.")]
public void Metodo();

[Serializable]
public class Classe();

[WebMethod]
public static void Listar();

These key names above each method name or class declaration are the attributes and serve to identify and classify classes and their fields according to some criteria, assigning them specific properties for use in the context in which they are used.

For example, the Obsolete attribute lets you define a message indicating that the method is deprecated and which one to use instead.

Source: Working with class attributes and Reflection in C # , in this article the author teaches you to create your own custom attribute, I recommend reading.

    
23.12.2014 / 12:00