diff --git a/docs/csharp/language-reference/attributes/general.md b/docs/csharp/language-reference/attributes/general.md index 443fdda24d07a..9821ef126b1b7 100644 --- a/docs/csharp/language-reference/attributes/general.md +++ b/docs/csharp/language-reference/attributes/general.md @@ -1,6 +1,6 @@ --- title: "Attributes interpreted by the compiler: Miscellaneous" -ms.date: 11/22/2024 +ms.date: 01/24/2025 description: "Learn about attributes that affect code generated by the compiler: the Conditional, Obsolete, AttributeUsage, ModuleInitializer, and SkipLocalsInit attributes." --- # Miscellaneous attributes interpreted by the C# compiler @@ -8,7 +8,10 @@ description: "Learn about attributes that affect code generated by the compiler: There are several attributes that can be applied to elements in your code that add semantic meaning to those elements: - [`Conditional`](#conditional-attribute): Make execution of a method dependent on a preprocessor identifier. -- [`Obsolete`](#obsolete-attribute): Mark a type or member for (potential) future removal. +- [`Obsolete`](#obsolete-and-deprecated-attribute): Mark a type or member for (potential) future removal. +- [`Deprecated`](#obsolete-and-deprecated-attribute): (Windows Foundation) Mark a type or member for (potential) future removal. +- [`Experimental`](#experimental-attributes): Mark a type or member as experimental. +- [`SetsRequiredMembers`](#setsrequiredmembers-attribute): Indicate that a constructor sets all required properties. - [`AttributeUsage`](#attributeusage-attribute): Declare the language elements where an attribute can be applied. - [`AsyncMethodBuilder`](#asyncmethodbuilder-attribute): Declare an async method builder type. - [`InterpolatedStringHandler`](#interpolatedstringhandler-and-interpolatedstringhandlerarguments-attributes): Define an interpolated string builder for a known scenario. @@ -16,7 +19,11 @@ There are several attributes that can be applied to elements in your code that a - [`SkipLocalsInit`](#skiplocalsinit-attribute): Elide the code that initializes local variable storage to 0. - [`UnscopedRef`](#unscopedref-attribute): Declare that a `ref` variable normally interpreted as `scoped` should be treated as unscoped. - [`OverloadResolutionPriority`](#overloadresolutionpriority-attribute): Add a tiebreaker attribute to influence overload resolution for possibly ambiguous overloads. -- [`Experimental`](#experimental-attribute): Mark a type or member as experimental. +- [`EnumeratorCancellation`](#enumeratorcancellation-attribute): Specify the parameter for a cancellation token in an async enumerator. +- [`CollectionBuilder`](#collectionbuilder-attribute): Specify the builder method for a collection type when a collection expression is converted to that collection type. +- [`InlineArray`](#inlinearray-attribute): Specify that a `struct` type is an *inline array*. +- [`IUnknownConstant`](#iunknownconstant-and-idispatchconstant-attributes): Specifies how a missing argument should be supplied for a default parameter. +- [`IDispatchConstant`](#iunknownconstant-and-idispatchconstant-attributes): Specifies how a missing argument should be supplied for a default parameter. The compiler uses those semantic meanings to alter its output and report possible mistakes by developers using your code. @@ -46,7 +53,7 @@ The `Conditional` attribute can also be applied to an attribute class definition :::code language="csharp" source="snippets/ConditionalExamples.cs" ID="SnippetConditionalConditionalAttribute" ::: -## `Obsolete` attribute +## `Obsolete` and `Deprecated` attribute 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 . @@ -58,15 +65,19 @@ The string provided as the first argument to the attribute constructor is displa :::code language="csharp" source="snippets/ObsoleteExample.cs" id="Snippet2" ::: -## `Experimental` attribute +The Windows Foundation Metadata libraries use the instead of the `ObsoleteAttribute`. + +## `Experimental` attributes Beginning in C# 12, types, methods, and assemblies can be marked with the to indicate an experimental feature. The compiler issues a warning if you access a method or type annotated with the . All types declared in an assembly or module marked with the `Experimental` attribute are experimental. The compiler issues a warning if you access any of them. You can disable these warnings to pilot an experimental feature. > [!WARNING] -> Experimental features are subject to changes. The APIs may change, or they may be removed in future updates. Including experimental features is a way for library authors to get feedback on ideas and concepts for future development. Use extreme caution when using any feature marked as experimental. +> Experimental features are subject to changes. The APIs can change, or they can be removed in future updates. Including experimental features is a way for library authors to get feedback on ideas and concepts for future development. Use extreme caution when using any feature marked as experimental. You can learn more about how APIs are marked as experimental in our article on [preview APIs](../../../fundamentals/runtime-libraries/preview-apis.md#experimentalattribute). You can read more details about the `Experimental` attribute in the [feature specification](~/_csharplang/proposals/csharp-12.0/experimental-attribute.md). +The Windows Foundation Metadata libraries use the , which predates C# 12. + ## `SetsRequiredMembers` attribute The `SetsRequiredMembers` attribute informs the compiler that a constructor sets all `required` members in that class or struct. The compiler assumes any constructor with the attribute initializes all `required` members. Any code that invokes such a constructor doesn't need object initializers to set required members. Adding the `SetsRequiredMembers` attribute is primarily useful for positional records and primary constructors. @@ -242,6 +253,22 @@ Overload resolution considers the two methods equally good for some argument typ All overloads with a lower priority than the highest overload priority are removed from the set of applicable methods. Methods without this attribute have the overload priority set to the default of zero. Library authors should use this attribute as a last resort when adding a new and better method overload. Library authors should have a deep understanding of how [Overload resolution](~/_csharplang/proposals/csharp-13.0/overload-resolution-priority.md#overload-resolution-priority) impacts choosing the better method. Otherwise, unexpected errors can result. +## EnumeratorCancellation attribute + +The attribute specifies which parameter should receive the cancellation token from the API. It's part of the infrastructure for the [async streams](../../asynchronous-programming/generate-consume-asynchronous-stream.md) feature. + +## CollectionBuilder attribute + +The attribute specifies a method that builds an instance of a collection type from a [collection expression](../operators/collection-expressions.md). You use this attribute to specify a method that builds the collection. The compiler generates code to call that method when a collection expression is converted to that type. + +## InlineArray attribute + +The attribute marks a type as an [inline array](../builtin-types/struct.md#inline-arrays). You can learn more about this feature in the article on `structs`, in the section on [inline arrays](../builtin-types/struct.md#inline-arrays). + +## IUnknownConstant and IDispatchConstant attributes + +The and attributes can be added to default parameters to indicate that a missing argument should be supplied as `new UnknownWrapper(null)` or `new DispatchWrapper(null)`. + ## See also - diff --git a/docs/csharp/language-reference/attributes/pseudo-attributes.md b/docs/csharp/language-reference/attributes/pseudo-attributes.md new file mode 100644 index 0000000000000..6634c52d8f1b5 --- /dev/null +++ b/docs/csharp/language-reference/attributes/pseudo-attributes.md @@ -0,0 +1,55 @@ +--- +title: "Attributes interpreted by the compiler: Pseudo-attributes" +ms.date: 01/2/2025 +description: "Learn about attributes you can add to code that are written to IL as modifiers. These custom attributes aren't emitted as attributes in the compiled output." +--- +# Custom attributes that generate flags or options in the Intermediate Language (IL) output + +You add these attributes to your code for the compiler to emit a specified Intermediate Language (IL) modifier. These attributes instruct the compiler to include the corresponding IL modifier in the output. + +| Attribute | Modifier | Comments | +|--------------------------------------------------------------------------------------|-----------------|-----------| +| | `import` | | +| | `pinvokeimpl` | You can add options listed in the constructor. | +| | `.field` | This sets the field offset for memory layout. | +| | `marshal` | You can set options listed in the constructor. | +| | `flag` | Constructor arguments specify specific named flags such as `aggressiveinlining` or `forwardref`. These flags also specify the `native`, `managed`, or `optil` modifiers for the field. | +| | `notserialized` | | +| | `[opt]` | | +| | `[out]` | | +| | `preservesig` | | +| | `serializable` | | +| | `auto`, `sequential`, or `explicit` | Layout options can be set using the parameters. | +| | | You add this attribute to an indexer to set a different method name. By default, indexers are compiled to a property named `Item`. You can specify a different name using this attribute. | + +Some of these custom attributes are applied using other C# syntax rather than adding the attribute to your source code. + +| Attribute | Comments | +|--------------------------------------------------------------------------------------------------|----------| +| | Specifies the default value for the parameter. Use the [default parameter syntax](../../methods.md#optional-parameters-and-arguments). | +| | Specifies the IL `[in]` modifier. Use the [`in`](../keywords/method-parameters.md#in-parameter-modifier) or [`ref readonly`](../keywords/method-parameters.md#ref-readonly-modifier). | +| | Specifies the IL `specialname` modifier. The compiler automatically adds this modifier for methods that require it. | +| | This attribute is required for the `delegate*` feature. The compiler adds it to any [`delegate*`](../unsafe-code.md#function-pointers) that requires its use. | + +The following custom attributes are generally disallowed in C# source. They're listed here to aid library authors who use reflection, and to ensure you don't create custom attributes with the same name. + +| Attribute | Comments | +|--------------------------------------------------------------------------------------------------|---------| +| | Prevents downlevel compilers from using metadata it can't safely understand. | +| | Encodes `const decimal` fields. The runtime doesn't support `decimal` values as constant values. | +| | Encodes indexers with . This attribute notes the default indexer when its name is different than `Item`. This attribute is allowed in source. | +| | Encodes whether a type in a signature is `dynamic` (versus `object`). | +| | This attribute notes extension methods. The compiler also places this attribute on the containing classes. | +| | This attribute specifies `fixed` struct fields. | +| | This attribute specifies a `ref` struct. | +| | This attribute indicates that a parameter has the `in` modifier. It distinguishes `in` parameters from `readonly ref` or `[In] ref`. | +| | This attribute indicates that a parameter has the `readonly ref` modifier. It distinguishes `readonly ref` from `in` or `[In] ref`. | +| | This attribute specifies the `unmanaged` constraint on a type parameter. | +| , , | These attributes encode nullable annotations in your source code. | +| | This attribute encodes the `params` modifier on array parameters. | +| | This attribute encodes the `params` modifier on non-array parameters. | +| | This attribute specifies the C# version that is required in order to understand ref safety annotations in the assembly. Ref safety rules evolve as C# gets new features. | +| | This attribute indicates that the `required` modifier was placed on a member declaration. It's the encoding of the [required members](../keywords/required.md) language feature. | +| | This attribute encodes tuple element names used in signatures. | + +In addition, the compiler can generate a declaration for other attributes used internally. The compiler generates these in the namespace for its own use. Some aren't in the .NET Runtime libraries. Instead, the compiler synthesizes a definition for an `internal` type declaration in any assembly where the attribute is needed. diff --git a/docs/csharp/language-reference/toc.yml b/docs/csharp/language-reference/toc.yml index 9aaea86ee02e4..fbbd94d62a0f1 100644 --- a/docs/csharp/language-reference/toc.yml +++ b/docs/csharp/language-reference/toc.yml @@ -380,17 +380,35 @@ items: - name: Attributes read by the compiler items: - name: Global attributes - displayName: AssemblyName, AssemblyVersion, AssemblyCulture, AssemblyFlags, AssemblyProduct, AssemblyTrademark, AssemblyInformationalVersion, AssemblyCompany, AssemblyCopyright, AssemblyFileVersion, CLSCompliant, AssemblyTitle, AssemblyDescription, AssemblyConfiguration, AssemblyDefaultAlias + displayName: > + AssemblyName, AssemblyVersion, AssemblyCulture, AssemblyFlags, AssemblyProduct, AssemblyTrademark, AssemblyInformationalVersion, + AssemblyCompany, AssemblyCopyright, AssemblyFileVersion, CLSCompliant, AssemblyTitle, AssemblyDescription, AssemblyConfiguration, + AssemblyDefaultAlias href: ./attributes/global.md - name: Caller information - displayName: CallerFilePath, CallerLineNumber, CallerMemberName + displayName: CallerFilePath, CallerLineNumber, CallerMemberName, CallerArgumentExpressionAttribute href: ./attributes/caller-information.md - name: Nullable static analysis - displayName: AllowNull, DisallowNull, MaybeNull, NotNull, MaybeNullWhen, NotNullWhen, NotNullIfNotNull, DoesNotReturn, DoesNotReturnIf + displayName: > + AllowNull, DisallowNull, MaybeNull, NotNull, MaybeNullWhen, NotNullWhen, NotNullIfNotNull, MemberNotNull, MemberNotNullIf, + DoesNotReturn, DoesNotReturnIf href: ./attributes/nullable-analysis.md - name: Miscellaneous - displayName: Conditional, Obsolete, Experimental, SetsRequiredMembers, AttributeUsage, ModuleInitializer, SkipLocalsInit, module initializer + displayName: > + Conditional, Obsolete, Deprecated, Experimental, SetsRequiredMembers, AttributeUsage, AsyncMethodBuilder, InterpolatedStringHandler, + ModuleInitializer, SkipLocalsInit, UnscopedRef, OverloadResolutionPriority. EnumeratorCancellation, CollectionBuilder, + IUnknownConstant, IDispatchConstant, module initializer href: ./attributes/general.md + - name: Pseudo-attributes + displayName: > + ComImportAttribute, DllImportAttribute, FieldOffsetAttribute, MarshalAsAttribute, MethodImplAttribute, NonSerializedAttribute, + OptionalAttribute, OutAttribute, PreserveSigAttribute, SerializableAttribute, StructLayoutAttribute, IndexerNameAttribute, + DefaultParameterValueAttribute, InAttribute, SpecialNameAttribute, UnmanagedCallersOnlyAttribute, CompilerFeatureRequiredAttribute, + DecimalConstantAttribute, DefaultMemberAttribute, DynamicAttribute, ExtensionAttribute, FixedBufferAttribute, IsByRefLikeAttribute, + IsReadOnlyAttribute, RequiresLocationAttribute, IsUnmanagedAttribute, NullableAttribute, NullableContextAttribute, + NullablePublicOnlyAttribute, ParamArrayAttribute, ParamCollectionAttribute, RefSafetyRulesAttribute, RequiredMemberAttribute, + TupleElementNamesAttribute + href: ./attributes/pseudo-attributes.md - name: Unsafe code and pointers displayName: unsafe code, pointers, fixed size buffer, function pointer href: ./unsafe-code.md diff --git a/docs/csharp/misc/cs0612.md b/docs/csharp/misc/cs0612.md index e9076746b7e10..28e9786a7500b 100644 --- a/docs/csharp/misc/cs0612.md +++ b/docs/csharp/misc/cs0612.md @@ -12,7 +12,7 @@ ms.assetid: 7695f3b7-ffef-43f7-83db-fc1a9e361f1a 'member' is obsolete - The class designer marked a member with the [Obsolete attribute](../language-reference/attributes/general.md#obsolete-attribute). This means that the member might not be supported in a future version of the class. + The class designer marked a member with the [Obsolete attribute](../language-reference/attributes/general.md#obsolete-and-deprecated-attribute). This means that the member might not be supported in a future version of the class. The following sample shows how accessing an obsolete member generates CS0612: diff --git a/docs/csharp/misc/cs0619.md b/docs/csharp/misc/cs0619.md index 44db309783acc..cc127f46442f9 100644 --- a/docs/csharp/misc/cs0619.md +++ b/docs/csharp/misc/cs0619.md @@ -12,7 +12,7 @@ ms.assetid: a2060eb1-cda5-493c-b049-9b1792f88207 'member' is obsolete: 'text' -A class member was marked with the [Obsolete](../language-reference/attributes/general.md#obsolete-attribute) attribute, such that an error will be issued when the class member is referenced. +A class member was marked with the [Obsolete](../language-reference/attributes/general.md#obsolete-and-deprecated-attribute) attribute, such that an error will be issued when the class member is referenced. ## Example diff --git a/docs/csharp/specification/toc.yml b/docs/csharp/specification/toc.yml index c27820c49c809..888f1ec5ec335 100644 --- a/docs/csharp/specification/toc.yml +++ b/docs/csharp/specification/toc.yml @@ -223,6 +223,8 @@ items: items: - name: Default interface methods href: ../../../_csharplang/proposals/csharp-8.0/default-interface-methods.md + - name: Variance safety for static interface members + href: ../../../_csharplang/proposals/csharp-9.0/variance-safety-for-static-interface-members.md - name: Static abstracts in interfaces href: ../../../_csharplang/proposals/csharp-11.0/static-abstracts-in-interfaces.md - name: Allow ref struct interfaces diff --git a/docs/csharp/versioning.md b/docs/csharp/versioning.md index d73523522f17a..ff22006f2435c 100644 --- a/docs/csharp/versioning.md +++ b/docs/csharp/versioning.md @@ -46,7 +46,7 @@ Here are some things to consider when trying to maintain backwards compatibility will have to be updated. This is a huge breaking change and is strongly discouraged. - Method signatures: When updating a method behavior requires you to change its signature as well, you should instead create an overload so that code calling into that method will still work. You can always manipulate the old method signature to call into the new method signature so that implementation remains consistent. -- [Obsolete attribute](language-reference/attributes/general.md#obsolete-attribute): You can use this attribute in your code to specify classes or class members that are deprecated and likely to be removed in future versions. This ensures developers utilizing your library are better prepared for breaking changes. +- [Obsolete attribute](language-reference/attributes/general.md#obsolete-and-deprecated-attribute): You can use this attribute in your code to specify classes or class members that are deprecated and likely to be removed in future versions. This ensures developers utilizing your library are better prepared for breaking changes. - Optional Method Arguments: When you make previously optional method arguments compulsory or change their default value then all code that does not supply those arguments will need to be updated. > [!NOTE] diff --git a/docs/csharp/whats-new/csharp-12.md b/docs/csharp/whats-new/csharp-12.md index d3b37c628d420..bd9958348aaf5 100644 --- a/docs/csharp/whats-new/csharp-12.md +++ b/docs/csharp/whats-new/csharp-12.md @@ -138,7 +138,7 @@ The difference is that the compiler can take advantage of known information abou ## Experimental attribute -Types, methods, or assemblies can be marked with the to indicate an experimental feature. The compiler issues a warning if you access a method or type annotated with the . All types included in an assembly marked with the `Experimental` attribute are experimental. You can read more in the article on [General attributes read by the compiler](../language-reference/attributes/general.md#experimental-attribute), or the [feature specification](~/_csharplang/proposals/csharp-12.0/experimental-attribute.md). +Types, methods, or assemblies can be marked with the to indicate an experimental feature. The compiler issues a warning if you access a method or type annotated with the . All types included in an assembly marked with the `Experimental` attribute are experimental. You can read more in the article on [General attributes read by the compiler](../language-reference/attributes/general.md#experimental-attributes), or the [feature specification](~/_csharplang/proposals/csharp-12.0/experimental-attribute.md). ## Interceptors diff --git a/docs/fundamentals/networking/http/httpclient-guidelines.md b/docs/fundamentals/networking/http/httpclient-guidelines.md index a0dc237ef6d81..82f38d833ec0c 100644 --- a/docs/fundamentals/networking/http/httpclient-guidelines.md +++ b/docs/fundamentals/networking/http/httpclient-guidelines.md @@ -94,7 +94,7 @@ The preceding code: - Instantiates an `HttpClient` given the `resilienceHandler`. > [!IMPORTANT] -> The `Microsoft.Extensions.Http.Resilience` library is currently marked as [experimental](../../../csharp/language-reference/attributes/general.md#experimental-attribute) and it may change in the future. +> The `Microsoft.Extensions.Http.Resilience` library is currently marked as [experimental](../../../csharp/language-reference/attributes/general.md#experimental-attributes) and it may change in the future. ## See also diff --git a/docs/fundamentals/runtime-libraries/preview-apis.md b/docs/fundamentals/runtime-libraries/preview-apis.md index 0ce64693a5944..2b8cd782ac1e2 100644 --- a/docs/fundamentals/runtime-libraries/preview-apis.md +++ b/docs/fundamentals/runtime-libraries/preview-apis.md @@ -52,7 +52,7 @@ When building against an experimental API, the compiler produces an error. Each Since each experimental feature has a separate ID, consenting to using one experimental feature doesn't consent to using another. -For more information, see [Experimental features][experimental-overview]. +For more information, see [Experimental features][experimental-overview] and the article in the C# guide on [general attributes](../../csharp/language-reference/attributes/general.md#experimental-attributes). ## Guidance for library developers