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