Skip to content

Commit 06c5a1c

Browse files
BillWagnerpkulikov
andauthored
Reorganize and update language reference for attributes processed by the C# compiler, including nullable analysis (#17776)
* Create outlines for new content - update TOC - Add stub outlines for new content. * port global attribute content * port general attributes - Add description for general attributes - Move samples from /samples/snippets - Add interactivity where possible. * remove links, move existing content. * fix a build warning * fix warnings * off by one folder * finished updating caller information * move existing nullable attribute content Also, update the title of the existing content * proofread and add new attributes * fix titles * Apply suggestions from code review Co-Authored-By: Petr Kulikov <[email protected]> * fix build warnings. Co-authored-by: Petr Kulikov <[email protected]>
1 parent 88f94e5 commit 06c5a1c

26 files changed

+703
-665
lines changed

.openpublishing.redirection.json

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1081,6 +1081,10 @@
10811081
"source_path": "docs/csharp/programming-guide/arrays/passing-arrays-using-ref-and-out.md",
10821082
"redirect_url": "/dotnet/csharp/programming-guide/arrays"
10831083
},
1084+
{
1085+
"source_path": "docs/csharp/programming-guide/concepts/caller-information.md",
1086+
"redirect_url": "/dotnet/csharp/language-reference/attributes/caller-information"
1087+
},
10841088
{
10851089
"source_path": "docs/csharp/programming-guide/classes-and-structs/how-to-access-a-collection-class-with-foreach.md",
10861090
"redirect_url": "/dotnet/csharp/language-reference/keywords/foreach-in"
@@ -1139,6 +1143,14 @@
11391143
"source_path": "docs/csharp/programming-guide/concepts/async/asynchronous-programming-with-async-and-await.md",
11401144
"redirect_url": "/dotnet/csharp/async/"
11411145
},
1146+
{
1147+
"source_path": "docs/csharp/programming-guide/concepts/attributes/attributeusage.md",
1148+
"redirect_url": "/dotnet/csharp/language-reference/attributes/general"
1149+
},
1150+
{
1151+
"source_path": "docs/csharp/programming-guide/concepts/attributes/common-attributes.md",
1152+
"redirect_url": "/dotnet/csharp/language-reference/attributes/global"
1153+
},
11421154
{
11431155
"source_path": "docs/csharp/programming-guide/concepts/linq/advanced-query-techniques-linq-to-xml.md",
11441156
"redirect_url": "/dotnet/csharp/programming-guide/concepts/linq/how-to-join-two-collections-linq-to-xml"
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
---
2+
title: "C# Reserved attributes: Tracking caller information"
3+
ms.date: 04/09/2020
4+
description: These attributes instruct the compiler to generate information about the code that calls a member. You use the CallerFilePath, CallerLineNumber, and CallerMemberName to provide detailed trace information
5+
---
6+
7+
# Reserved attributes: Determine caller information
8+
9+
Using info attributes, you obtain information about the caller to a method. You obtain the file path of the source code, the line number in the source code, and the member name of the caller. To obtain member caller information, you use attributes that are applied to optional parameters. Each optional parameter specifies a default value. The following table lists the Caller Info attributes that are defined in the <xref:System.Runtime.CompilerServices?displayProperty=nameWithType> namespace:
10+
11+
|Attribute|Description|Type|
12+
|---|---|---|
13+
|<xref:System.Runtime.CompilerServices.CallerFilePathAttribute>|Full path of the source file that contains the caller. The full path is the path at compile time.|`String`|
14+
|<xref:System.Runtime.CompilerServices.CallerLineNumberAttribute>|Line number in the source file from which the method is called.|`Integer`|
15+
|<xref:System.Runtime.CompilerServices.CallerMemberNameAttribute>|Method name or property name of the caller.|`String`|
16+
17+
This information helps you write tracing, debugging, and create diagnostic tools. The following example shows how to use caller info attributes. On each call to the `TraceMessage` method, the caller information is substituted as arguments to the optional parameters.
18+
19+
```csharp
20+
public void DoProcessing()
21+
{
22+
TraceMessage("Something happened.");
23+
}
24+
25+
public void TraceMessage(string message,
26+
[CallerMemberName] string memberName = "",
27+
[CallerFilePath] string sourceFilePath = "",
28+
[CallerLineNumber] int sourceLineNumber = 0)
29+
{
30+
Trace.WriteLine("message: " + message);
31+
Trace.WriteLine("member name: " + memberName);
32+
Trace.WriteLine("source file path: " + sourceFilePath);
33+
Trace.WriteLine("source line number: " + sourceLineNumber);
34+
}
35+
36+
// Sample Output:
37+
// message: Something happened.
38+
// member name: DoProcessing
39+
// source file path: c:\Visual Studio Projects\CallerInfoCS\CallerInfoCS\Form1.cs
40+
// source line number: 31
41+
```
42+
43+
You specify an explicit default value for each optional parameter. You can't apply caller info attributes to parameters that aren't specified as optional. The caller info attributes don't make a parameter optional. Instead, they affect the default value that's passed in when the argument is omitted. Caller info values are emitted as literals into the Intermediate Language (IL) at compile time. Unlike the results of the <xref:System.Exception.StackTrace%2A> property for exceptions, the results aren't affected by obfuscation. You can explicitly supply the optional arguments to control the caller information or to hide caller information.
44+
45+
### Member names
46+
47+
You can use the `CallerMemberName` attribute to avoid specifying the member name as a `String` argument to the called method. By using this technique, you avoid the problem that **Rename Refactoring** doesn't change the `String` values. This benefit is especially useful for the following tasks:
48+
49+
- Using tracing and diagnostic routines.
50+
- Implementing the <xref:System.ComponentModel.INotifyPropertyChanged> interface when binding data. This interface allows the property of an object to notify a bound control that the property has changed, so that the control can display the updated information. Without the `CallerMemberName` attribute, you must specify the property name as a literal.
51+
52+
The following chart shows the member names that are returned when you use the `CallerMemberName` attribute.
53+
54+
|Calls occur within|Member name result|
55+
|-|-|
56+
|Method, property, or event|The name of the method, property, or event from which the call originated.|
57+
|Constructor|The string ".ctor"|
58+
|Static constructor|The string ".cctor"|
59+
|Destructor|The string "Finalize"|
60+
|User-defined operators or conversions|The generated name for the member, for example, "op_Addition".|
61+
|Attribute constructor|The name of the method or property to which the attribute is applied. If the attribute is any element within a member (such as a parameter, a return value, or a generic type parameter), this result is the name of the member that's associated with that element.|
62+
|No containing member (for example, assembly-level or attributes that are applied to types)|The default value of the optional parameter.|
63+
64+
## See also
65+
66+
- [Named and Optional Arguments](../../programming-guide/classes-and-structs/named-and-optional-arguments.md)
67+
- <xref:System.Reflection>
68+
- <xref:System.Attribute>
69+
- [Attributes](../../../standard/attributes/index.md)
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
---
2+
title: "C# reserved attributes: Conditional, Obsolete, AttributeUsage"
3+
ms.date: 04/09/2020
4+
description: These attributes are interpreted by the compiler to affect the code generated by the compiler
5+
---
6+
# Reserved attributes: ConditionalAttribute, ObsoleteAttribute, AttributeUsageAttribute
7+
8+
These attributes can be applied to elements in your code. They add semantic meaning to those elements. The compiler uses those semantic meanings to alter its output and report possible mistakes by developers using your code.
9+
10+
## `Conditional` attribute
11+
12+
The `Conditional` attribute makes the execution of a method dependent on a preprocessing identifier. The `Conditional` attribute is an alias for <xref:System.Diagnostics.ConditionalAttribute>, and can be applied to a method or an attribute class.
13+
14+
In the following example, `Conditional` is applied to a method to enable or disable the display of program-specific diagnostic information:
15+
16+
::::::code language="csharp" source="snippets/trace.cs" interactive="try-dotnet" :::
17+
18+
If the `TRACE_ON` identifier isn't defined, the trace output isn't displayed. Explore for yourself in the interactive window.
19+
20+
The `Conditional` attribute is often used with the `DEBUG` identifier to enable trace and logging features for debug builds but not in release builds, as shown in the following example:
21+
22+
::::::code language="csharp" source="snippets/ConditionalExamples.cs" id="SnippetConditional" :::
23+
24+
When a method marked conditional is called, the presence or absence of the specified preprocessing symbol determines whether the call is included or omitted. If the symbol is defined, the call is included; otherwise, the call is omitted. A conditional method must be a method in a class or struct declaration and must have a `void` return type. Using `Conditional` is cleaner, more elegant, and less error-prone than enclosing methods inside `#if…#endif` blocks.
25+
26+
If a method has multiple `Conditional` attributes, a call to the method is included if at one or more conditional symbols is defined (the symbols are logically linked together by using the OR operator). In the following example, the presence of either `A` or `B` results in a method call:
27+
28+
::::::code language="csharp" source="snippets/ConditionalExamples.cs" id="SnippetMultipleConditions" :::
29+
30+
### Using `Conditional` with attribute classes
31+
32+
The `Conditional` attribute can also be applied to an attribute class definition. In the following example, the custom attribute `Documentation` will only add information to the metadata if `DEBUG` is defined.
33+
34+
::::::code language="csharp" source="snippets/ConditionalExamples.cs" id="SnippetConditionalConditionalAttribute" :::
35+
36+
## `Obsolete` attribute
37+
38+
The `Obsolete` attribute marks a code element as no longer recommended for use. Use of an entity marked obsolete generates a warning or an error. The `Obsolete` attribute is a single-use attribute and can be applied to any entity that allows attributes. `Obsolete` is an alias for <xref:System.ObsoleteAttribute>.
39+
40+
In the following example the `Obsolete` attribute is applied to class `A` and to method `B.OldMethod`. Because the second argument of the attribute constructor applied to `B.OldMethod` is set to `true`, this method will cause a compiler error, whereas using class `A` will just produce a warning. Calling `B.NewMethod`, however, produces no warning or error. For example, when you use it with the previous definitions, the following code generates two warnings and one error:
41+
42+
::::::code language="csharp" source="snippets/ObsoleteExample.cs" interactive="try-dotnet" :::
43+
44+
The string provided as the first argument to the attribute constructor will be displayed as part of the warning or error. Two warnings for class `A` are generated: one for the declaration of the class reference, and one for the class constructor. The `Obsolete` attribute can be used without arguments, but including an explanation what to use instead is recommended.
45+
46+
## `AttributeUsage` attribute
47+
48+
The `AttributeUsage` attribute determines how a custom attribute class can be used. <xref:System.AttributeUsageAttribute> is an attribute you apply to custom attribute definitions. The `AttributeUsage` attribute enables you to control:
49+
50+
- Which program elements attribute may be applied to. Unless you restrict its usage, an attribute may be applied to any of the following program elements:
51+
- assembly
52+
- module
53+
- field
54+
- event
55+
- method
56+
- param
57+
- property
58+
- return
59+
- type
60+
- Whether an attribute can be applied to a single program element multiple times.
61+
- Whether attributes are inherited by derived classes.
62+
63+
The default settings look like the following example when applied explicitly:
64+
65+
:::code language="csharp" source="snippets/NewAttribute.cs" id="SnippetUsageFirst" :::
66+
67+
In this example, the `NewAttribute` class can be applied to any supported program element. But it can be applied only once to each entity. The attribute is inherited by derived classes when applied to a base class.
68+
69+
The <xref:System.AttributeUsageAttribute.AllowMultiple> and <xref:System.AttributeUsageAttribute.Inherited> arguments are optional, so the following code has the same effect:
70+
71+
:::code language="csharp" source="snippets/NewAttribute.cs" id="SnippetUsageSecond" :::
72+
73+
The first <xref:System.AttributeUsageAttribute> argument must be one or more elements of the <xref:System.AttributeTargets> enumeration. Multiple target types can be linked together with the OR operator, like the following example shows:
74+
75+
:::code language="csharp" source="snippets/NewPropertyOrFieldAttribute.cs" id="SnippetDefinePropertyAttribute" :::
76+
77+
Beginning in C# 7.3, attributes can be applied to either the property or the backing field for an auto-implemented property. The attribute applies to the property, unless you specify the `field` specifier on the attribute. Both are shown in the following example:
78+
79+
:::code language="csharp" source="snippets/NewPropertyOrFieldAttribute.cs" id="SnippetUsePropertyAttribute" :::
80+
81+
If the <xref:System.AttributeUsageAttribute.AllowMultiple> argument is `true`, then the resulting attribute can be applied more than once to a single entity, as shown in the following example:
82+
83+
:::code language="csharp" source="snippets/MultiUseAttribute.cs" id="SnippetMultiUse" :::
84+
85+
In this case, `MultiUseAttribute` can be applied repeatedly because `AllowMultiple` is set to `true`. Both formats shown for applying multiple attributes are valid.
86+
87+
If <xref:System.AttributeUsageAttribute.Inherited> is `false`, then the attribute isn't inherited by classes derived from an attributed class. For example:
88+
89+
:::code language="csharp" source="snippets/NonInheritedAttribute.cs" id="SnippetNonInherited" :::
90+
91+
In this case `NonInheritedAttribute` isn't applied to `DClass` via inheritance.
92+
93+
## See also
94+
95+
- <xref:System.Attribute>
96+
- <xref:System.Reflection>
97+
- [Attributes](../../../standard/attributes/index.md)
98+
- [Reflection](../../programming-guide/concepts/reflection.md)
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
---
2+
title: "C# reserved attributes: Global attributes"
3+
ms.date: 04/09/2020
4+
description: Attributes provide metadata the compiler uses to understand more semantics of your program
5+
---
6+
# Reserved attributes: Assembly level attributes
7+
8+
Most attributes are applied to specific language elements such as classes or methods; however, some attributes are global—they apply to an entire assembly or module. For example, the <xref:System.Reflection.AssemblyVersionAttribute> attribute can be used to embed version information into an assembly, like this:
9+
10+
```csharp
11+
[assembly: AssemblyVersion("1.0.0.0")]
12+
```
13+
14+
Global attributes appear in the source code after any top level `using` directives and before any type, module, or namespace declarations. Global attributes can appear in multiple source files, but the files must be compiled in a single compilation pass. Visual Studio adds global attributes to the AssemblyInfo.cs file in .NET Framework projects. These attributes aren't added to .NET Core projects.
15+
16+
Assembly attributes are values that provide information about an assembly. They fall into the following categories:
17+
18+
- Assembly identity attributes
19+
- Informational attributes
20+
- Assembly manifest attributes
21+
22+
## Assembly identity attributes
23+
24+
Three attributes (with a strong name, if applicable) determine the identity of an assembly: name, version, and culture. These attributes form the full name of the assembly and are required when you reference it in code. You can set an assembly's version and culture using attributes. However, the name value is set by the compiler, the Visual Studio IDE in the [Assembly Information Dialog Box](/visualstudio/ide/reference/assembly-information-dialog-box), or the Assembly Linker (Al.exe) when the assembly is created. The assembly name is based on the assembly manifest. The <xref:System.Reflection.AssemblyFlagsAttribute> attribute specifies whether multiple copies of the assembly can coexist.
25+
26+
The following table shows the identity attributes.
27+
28+
|Attribute|Purpose|
29+
|---------------|-------------|
30+
|<xref:System.Reflection.AssemblyVersionAttribute>|Specifies the version of an assembly.|
31+
|<xref:System.Reflection.AssemblyCultureAttribute>|Specifies which culture the assembly supports.|
32+
|<xref:System.Reflection.AssemblyFlagsAttribute>|Specifies whether an assembly supports side-by-side execution on the same computer, in the same process, or in the same application domain.|
33+
34+
## Informational attributes
35+
36+
You use informational attributes to provide additional company or product information for an assembly. The following table shows the informational attributes defined in the <xref:System.Reflection?displayProperty=nameWithType> namespace.
37+
38+
|Attribute|Purpose|
39+
|---------------|-------------|
40+
|<xref:System.Reflection.AssemblyProductAttribute>|Specifies a product name for an assembly manifest.|
41+
|<xref:System.Reflection.AssemblyTrademarkAttribute>|Specifies a trademark for an assembly manifest.|
42+
|<xref:System.Reflection.AssemblyInformationalVersionAttribute>|Specifies an informational version for an assembly manifest.|
43+
|<xref:System.Reflection.AssemblyCompanyAttribute>|Specifies a company name for an assembly manifest.|
44+
|<xref:System.Reflection.AssemblyCopyrightAttribute>|Defines a custom attribute that specifies a copyright for an assembly manifest.|
45+
|<xref:System.Reflection.AssemblyFileVersionAttribute>|Sets a specific version number for the Win32 file version resource.|
46+
|<xref:System.CLSCompliantAttribute>|Indicates whether the assembly is compliant with the Common Language Specification (CLS).|
47+
48+
## Assembly manifest attributes
49+
50+
You can use assembly manifest attributes to provide information in the assembly manifest. The attributes include title, description, default alias, and configuration. The following table shows the assembly manifest attributes defined in the <xref:System.Reflection?displayProperty=nameWithType> namespace.
51+
52+
|Attribute|Purpose|
53+
|---------------|-------------|
54+
|<xref:System.Reflection.AssemblyTitleAttribute>|Specifies an assembly title for an assembly manifest.|
55+
|<xref:System.Reflection.AssemblyDescriptionAttribute>|Specifies an assembly description for an assembly manifest.|
56+
|<xref:System.Reflection.AssemblyConfigurationAttribute>|Specifies an assembly configuration (such as retail or debug) for an assembly manifest.|
57+
|<xref:System.Reflection.AssemblyDefaultAliasAttribute>|Defines a friendly default alias for an assembly manifest|

0 commit comments

Comments
 (0)