What are these attributes in the properties?

Asked

Viewed 667 times

10

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

Examples:

in the declaration of a class:

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

in the declaration of a property:

[XmlElement]
public string Valor
{
   get { return _valor; }
   set { _valor = value; }
}

3 answers

8


Have you seen in the other answers what is an attribute.

They can be used in:

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

An example of use in parameters.

void metodo([nonnull] string texto)

Using in Assembly:

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

As noted it is possible to 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
  • stop
  • Return

They are used to add metadata to the code. Something 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 yourself. Net and other Microsoft libraries or not, or use attributes you created.

Some of these attributes are used through reflection by libraries and most commonly by frameworks. It can be used by the compiler to change its behavior towards 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 points. "Listen" to the master.

Different syntax

Take this example

[ComVisibleAttribute(true)]

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

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

[ComVisible(true)]

But how? I went there on documentation and I saw 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 must end with the word Attribute to avoid conflicts. But to use the compiler more simply when you uses the attribute somewhere in the code the compiler searches 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 the XMLSerializer that that member is a member to be considered as XML. So it is an attribute created by . Net to assist one of its classes.

[Browsable(false)]

Determines whether the member will be visible in the IDE’s Properties window.

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

How to show that member when inspecting values in Debugger.

[Flags]

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

[Conditional("DEBUG")]

Determines in which type of release that code must be executed.

[Serializable]

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

[Optional]

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

[Test]

Indicates that the method is a unit test. Tools for this need to know what to run.

[assembly: InternalsVisibleTo("ClasseX")]

Do what the attribute does Friend of the C++.

Complete list created on . NET.

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

Parameters for attributes

It is not possible to 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 build time. You can use:

  • bool,
  • byte,
  • char,
  • double,
  • float,
  • int,
  • long,
  • shorts,
  • string
  • System Type.
  • Object
  • Enum (with restrictions)
  • array (with restrictions)

Example of use:

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);
            }
        }
    }
}

I put in the Github for future reference.

7

That’s the right name. Attributes, or in English, Attributes.

Attributes has several functions:

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

Here is an introduction to Attributes (in English).

2

[Obsolete("Não utilizar esse método.")]
public void Metodo();

[Serializable]
public class Classe();

[WebMethod]
public static void Listar();

These names between keys 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 attribute Obsolete allows to define a message indicating that the method is obsolete and indicating which to use instead.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.