diff --git a/.openpublishing.redirection.csharp.json b/.openpublishing.redirection.csharp.json index e9be684712504..17296c3eb6a6d 100644 --- a/.openpublishing.redirection.csharp.json +++ b/.openpublishing.redirection.csharp.json @@ -438,6 +438,10 @@ "source_path_from_root": "/docs/csharp/language-reference/compiler-messages/cs1502.md", "redirect_url": "/dotnet/csharp/misc/cs1503" }, + { + "source_path_from_root": "/docs/csharp/language-reference/compiler-messages/cs1546.md", + "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/indexer-access-errors" + }, { "source_path_from_root": "/docs/csharp/language-reference/compiler-messages/cs1564.md", "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/invalid-build-command-line" @@ -666,6 +670,10 @@ "source_path_from_root": "/docs/csharp/language-reference/compiler-messages/cs8418.md", "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/using-statement-declaration-errors#implementing-idisposable-and-iasyncdisposable" }, + { + "source_path_from_root": "/docs/csharp/language-reference/compiler-messages/cs8422.md", + "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/local-function-errors" + }, { "source_path_from_root": "/docs/csharp/language-reference/compiler-messages/cs8515.md", "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/pattern-matching-warnings" diff --git a/docs/csharp/language-reference/compiler-messages/attribute-usage-errors.md b/docs/csharp/language-reference/compiler-messages/attribute-usage-errors.md index 358e6c40aff86..dd8c0d8f8adee 100644 --- a/docs/csharp/language-reference/compiler-messages/attribute-usage-errors.md +++ b/docs/csharp/language-reference/compiler-messages/attribute-usage-errors.md @@ -38,13 +38,14 @@ f1_keywords: - "CS7046" - "CS7047" - "CS7067" + - "CS8423" + - "CS8783" - "CS8959" - "CS8960" - "CS8961" - "CS8962" - "CS8963" - "CS8968" - - "CS8783" - "CS8970" - "CS9331" helpviewer_keywords: @@ -84,16 +85,17 @@ helpviewer_keywords: - "CS7046" - "CS7047" - "CS7067" + - "CS8423" + - "CS8783" - "CS8959" - "CS8960" - "CS8961" - "CS8962" - "CS8963" - "CS8968" - - "CS8783" - "CS8970" - "CS9331" -ms.date: 05/19/2026 +ms.date: 07/16/2026 ai-usage: ai-assisted --- # Resolve errors and warnings related to attribute declarations or attribute use in your code @@ -139,13 +141,14 @@ That's by design. The text closely matches the text of the compiler error / warn - [**CS7046**](#attribute-arguments-and-parameters): *Attribute parameter must be specified.* - [**CS7047**](#attribute-arguments-and-parameters): *Attribute parameter 'parameter1' or 'parameter2' must be specified.* - [**CS7067**](#attribute-arguments-and-parameters): *Attribute constructor parameter is optional, but no default parameter value was specified.* +- [**CS8423**](#attribute-location-context): *Attribute 'attribute' is not valid on event accessors. It is only valid on 'declaration' declarations.* +- [**CS8783**](#conditional-attribute-usage): *Local function 'method' must be 'static' in order to use the Conditional attribute* - [**CS8959**](#callerargumentexpression-attribute-usage): *CallerArgumentExpressionAttribute cannot be applied because there are no standard conversions from type1 to type2* - [**CS8960**](#callerargumentexpression-attribute-usage): *The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is overridden by the CallerLineNumberAttribute.* - [**CS8961**](#callerargumentexpression-attribute-usage): *The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is overridden by the CallerFilePathAttribute.* - [**CS8962**](#callerargumentexpression-attribute-usage): *The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is overridden by the CallerMemberNameAttribute.* - [**CS8963**](#callerargumentexpression-attribute-usage): *The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is applied with an invalid parameter name.* - [**CS8968**](#attribute-arguments-and-parameters): *An attribute type argument cannot use type parameters* -- [**CS8783**](#conditional-attribute-usage): *Local function 'method' must be 'static' in order to use the Conditional attribute* - [**CS8970**](#attribute-arguments-and-parameters): *Type cannot be used in this context because it cannot be represented in metadata.* - [**CS9331**](#predefined-attributes): *Attribute cannot be applied manually.* @@ -210,6 +213,7 @@ The following errors occur when you apply attributes in invalid locations or use - **CS0658**: *Location is not a recognized attribute location. Valid attribute locations for this declaration are listed. All attributes in this block will be ignored.* - **CS1667**: *Attribute is not valid on property or event accessors. It is only valid on specific declarations.* - **CS7014**: *Attributes are not valid in this context.* +- **CS8423**: *Attribute 'attribute' is not valid on event accessors. It is only valid on 'declaration' declarations.* To correct these errors, follow these rules. For more information, see [Attribute Targets](../../advanced-topics/reflection-and-attributes/index.md#attribute-targets) and the [C# language specification section on attribute specification](~/_csharpstandard/standard/attributes.md#233-attribute-specification). @@ -218,6 +222,7 @@ To correct these errors, follow these rules. For more information, see [Attribut - The attribute target specifier you used isn't a recognized specifier (**CS0658**). Valid specifiers include `assembly:`, `module:`, `type:`, `method:`, `property:`, `field:`, `event:`, `param:`, and `return:`. - Some attributes, such as and , aren't valid on property or event accessors (**CS1667**). Move the attribute from the accessor to the property or event declaration itself. - Attributes can only appear on program elements that support them (**CS7014**). If you're applying assembly-level or module-level attributes, use the `assembly:` or `module:` target specifiers and place them at the top of the file. +- Attributes on event `add` and `remove` accessors aren't allowed (**CS8423**). Apply the attribute to the event declaration, or use a valid target such as `method:` or `param:` on a declaration that supports that target. ## Predefined attributes diff --git a/docs/csharp/language-reference/compiler-messages/cs1546.md b/docs/csharp/language-reference/compiler-messages/cs1546.md deleted file mode 100644 index 7e62e41d6c1a4..0000000000000 --- a/docs/csharp/language-reference/compiler-messages/cs1546.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -description: "Compiler Error CS1546" -title: "Compiler Error CS1546" -ms.date: 07/20/2015 -f1_keywords: - - "CS1546" -helpviewer_keywords: - - "CS1546" -ms.assetid: 15fe2cdc-954f-4c67-80fd-9903c464f361 ---- -# Compiler Error CS1546 - -Property, indexer, or event 'property' is not supported by the language; try directly calling accessor method 'accessor' - - Your code is consuming an object that has a default indexed property and tried to use the indexed syntax. To resolve this error, call the property's accessor method. For more information on indexers and properties, see [Indexers](../../programming-guide/indexers/index.md). - - The following sample generates CS1546. - -## Example 1 - - This code sample consists of a .cpp file, which compiles to a .dll, and a .cs file, which uses that .dll. The following code is for the .dll file and defines a property to be accessed by the code in the .cs file. - -```cpp -// CPP1546.cpp -// compile with: /clr /LD -using namespace System; -public ref class MCPP -{ -public: - property int Prop [int,int] - { - int get( int i, int b ) - { - return i; - } - } -}; -``` - -## Example 2 - - This is the C# file. - -```csharp -// CS1546.cs -// compile with: /r:CPP1546.dll -using System; -public class Test -{ - public static void Main() - { - int i = 0; - MCPP mcpp = new MCPP(); - i = mcpp.Prop(1,1); // CS1546 - // Try the following line instead: - // i = mcpp.get_Prop(1,1); - } -} -``` diff --git a/docs/csharp/language-reference/compiler-messages/cs8422.md b/docs/csharp/language-reference/compiler-messages/cs8422.md deleted file mode 100644 index 9b2209cf5f6b6..0000000000000 --- a/docs/csharp/language-reference/compiler-messages/cs8422.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -description: "Compiler Error CS8422" -title: "Compiler Error CS8422" -ms.date: 12/17/2023 -f1_keywords: - - "CS8422" -helpviewer_keywords: - - "CS8422" ---- -# Compiler Error CS8422 - -A static local function cannot contain a reference to 'this' or 'base'. - -The [`static`](../keywords/static.md) keyword on a local function prevents the local function from accessing the state of parent instance methods or instances fields. -
This error indicates the local function accesses instance members of the containing type. - -## Example - -The following sample generates CS8422: - -```csharp -public class C -{ - private int counter = 1; - public void IncreaseCounter() - { - static void localFunc(int addition) - { - this.counter += addition; // CS8422 due to reference to 'this' - base.ToString(); // CS8422 due to reference to 'base' - - // Also for implicit 'this' or 'base' references: - counter += addition; // CS8422 due to implicit reference to 'this' - ToString(); // CS8422 due to implicit reference to 'base' - } - localFunc(10); - Console.WriteLine(this.counter); - } -} -``` - -## To correct this error - -If there is an intention of local function to capture and modify the state of a parent then it shouldn't be declared static. You could also remove access to any instance members. - -```csharp -public class C -{ - private int counter = 1; - public void IncreaseCounter() - { - void localFunc(int addition) - { - counter += addition; - ToString(); - } - localFunc(10); - Console.WriteLine(this.counter); - } -} - -public class Program -{ - public void Main() - { - C c = new(); - c.IncreaseCounter(); - } -} - -// Output: -// 11 -``` - -## See also - -- [Local functions](../../programming-guide/classes-and-structs/local-functions.md) -- [CS0120](./cs0120.md) diff --git a/docs/csharp/language-reference/compiler-messages/indexer-access-errors.md b/docs/csharp/language-reference/compiler-messages/indexer-access-errors.md new file mode 100644 index 0000000000000..40029d8b48276 --- /dev/null +++ b/docs/csharp/language-reference/compiler-messages/indexer-access-errors.md @@ -0,0 +1,89 @@ +--- +title: "Resolve errors and warnings related to indexer and element access" +description: "This article helps you diagnose and correct compiler errors and warnings related to indexer and element access" +f1_keywords: + - "CS0021" + - "CS0154" + - "CS0271" + - "CS0272" + - "CS0856" + - "CS0857" + - "CS1545" + - "CS1546" + - "CS8428" + - "CS8429" +helpviewer_keywords: + - "CS0021" + - "CS0154" + - "CS0271" + - "CS0272" + - "CS0856" + - "CS0857" + - "CS1545" + - "CS1546" + - "CS8428" + - "CS8429" +ms.date: 07/16/2026 +ai-usage: ai-assisted +--- +# Resolve errors and warnings related to indexer and element access + +This article covers the following compiler errors and warnings: + + +- [**CS0021**](#indexing-non-indexable-types): *Cannot apply indexing with [] to an expression of type 'type'* +- [**CS0154**](#accessor-availability-and-accessibility): *The property or indexer 'indexer' cannot be used in this context because it lacks the get accessor* +- [**CS0271**](#accessor-availability-and-accessibility): *The property or indexer 'indexer' cannot be used in this context because the get accessor is inaccessible* +- [**CS0272**](#accessor-availability-and-accessibility): *The property or indexer 'indexer' cannot be used in this context because the set accessor is inaccessible* +- [**CS0856**](#indexed-properties-from-com-and-interop): *Indexed property 'indexer' has non-optional arguments which must be provided* +- [**CS0857**](#indexed-properties-from-com-and-interop): *Indexed property 'indexer' must have all arguments optional* +- [**CS1545**](#indexed-properties-from-com-and-interop): *Property, indexer, or event 'member' is not supported by the language; try directly calling accessor methods 'method' or 'method'* +- [**CS1546**](#indexed-properties-from-com-and-interop): *Property, indexer, or event 'member' is not supported by the language; try directly calling accessor method 'method'* +- [**CS8428**](#implicit-index-and-range-indexers): *Invocation of implicit Index Indexer cannot name the argument.* +- [**CS8429**](#implicit-index-and-range-indexers): *Invocation of implicit Range Indexer cannot name the argument.* + +These diagnostics cover element access expressions such as `value[index]`, explicit indexers, indexed properties imported from metadata or COM interop, and the implicit `Index` and `Range` indexers used by the `^` and `..` operators. + +## Indexing non-indexable types + +- **CS0021**: *Cannot apply indexing with [] to an expression of type 'type'* + +Use `[]` only with arrays, pointer types, or types that define an applicable indexer. If the type should support element access, add an indexer declaration to the type. Otherwise, call the member that retrieves the element, or convert the value to a type that supports indexing before using `[]`. + +## Accessor availability and accessibility + +- **CS0154**: *The property or indexer 'indexer' cannot be used in this context because it lacks the get accessor* +- **CS0271**: *The property or indexer 'indexer' cannot be used in this context because the get accessor is inaccessible* +- **CS0272**: *The property or indexer 'indexer' cannot be used in this context because the set accessor is inaccessible* + +Reading an indexer requires an accessible `get` accessor. Writing an indexer requires an accessible `set` or `init` accessor. Add the missing accessor, change the accessor accessibility, or use the indexer only in contexts where the required accessor is available. + +## Indexed properties from COM and interop + +- **CS0856**: *Indexed property 'indexer' has non-optional arguments which must be provided* +- **CS0857**: *Indexed property 'indexer' must have all arguments optional* +- **CS1545**: *Property, indexer, or event 'member' is not supported by the language; try directly calling accessor methods 'method' or 'method'* +- **CS1546**: *Property, indexer, or event 'member' is not supported by the language; try directly calling accessor method 'method'* + +Some metadata patterns, especially from COM or other .NET languages, expose indexed properties that C# can't bind with ordinary property or indexer syntax. Supply all required indexed property arguments when the metadata requires them (**CS0856**). When C# requires indexed property arguments to be optional, change the imported member or wrapper so all arguments are optional (**CS0857**). + +For unsupported imported properties, indexers, or events, call the generated accessor method directly from C# source when the accessor itself is callable (**CS1545**, **CS1546**). For example, call `get_Prop(arguments)` or `set_Prop(arguments, value)` instead of using property syntax when the member can't be represented directly in C#. + +## Implicit index and range indexers + +- **CS8428**: *Invocation of implicit Index Indexer cannot name the argument.* +- **CS8429**: *Invocation of implicit Range Indexer cannot name the argument.* + +The compiler can synthesize an indexer for the [index from end (`^`) and range (`..`) operators](../operators/member-access-operators.md#index-from-end-operator-) when a type has the required `Length` or `Count` member, an `int` indexer, or a compatible `Slice` method. Calls to those implicit `Index` or `Range` indexers must use positional arguments. Remove the argument name from the invocation and pass the `Index` or `Range` value positionally (**CS8428**, **CS8429**). + +## Related diagnostics + +- For more information about array indexing and rank, see [Resolve errors and warnings related to array and collection declarations and initializations](array-declaration-errors.md) in C# compiler messages. +- For more information about argument lists, see [Errors and warnings for parameter / argument mismatches](parameter-argument-mismatch.md) in C# compiler messages. +- For more information about overload resolution for indexers and element access, see [Fix errors that involve overload resolution](overload-resolution.md) in C# compiler messages. +- For more information about read-only and init-only properties, see [Compiler Errors on property declarations](property-declaration-errors.md) in C# compiler messages. +- For more information about dynamic binding, see [Resolve errors related to dynamic binding and the dynamic type](dynamic-type-and-binding-errors.md) in C# compiler messages. +- For more information about indexer access in expression trees, see [Some expressions are prohibited in expression trees](expression-tree-restrictions.md) in C# compiler messages. +- For more information about inline array element access, see [Resolve errors related to inline arrays](inline-array-errors.md) in C# compiler messages. diff --git a/docs/csharp/language-reference/compiler-messages/interface-implementation-errors.md b/docs/csharp/language-reference/compiler-messages/interface-implementation-errors.md index 339f09307e209..9629bd14e2304 100644 --- a/docs/csharp/language-reference/compiler-messages/interface-implementation-errors.md +++ b/docs/csharp/language-reference/compiler-messages/interface-implementation-errors.md @@ -22,6 +22,7 @@ f1_keywords: - "CS0736" - "CS0737" - "CS0738" + - "CS8646" - "CS8705" - "CS8854" - "CS9333" @@ -47,11 +48,12 @@ helpviewer_keywords: - "CS0736" - "CS0737" - "CS0738" + - "CS8646" - "CS8705" - "CS8854" - "CS9333" - "CS9334" -ms.date: 11/12/2025 +ms.date: 07/16/2026 ai-usage: ai-assisted --- # Resolve errors and warnings related to members that implement an interface @@ -81,6 +83,7 @@ That's by design. The text closely matches the text of the compiler error / warn - [**CS0736**](#method-visibility-and-modifiers): *Member does not implement instance interface member. It cannot implement the interface member because it is static.* - [**CS0737**](#method-visibility-and-modifiers): *Member does not implement interface member. It cannot implement an interface member because it is not public.* - [**CS0738**](#return-types-and-signatures): *Member does not implement interface member. It cannot because it does not have the matching return type.* +- [**CS8646**](#ambiguous-and-conflicting-implementations): *'member' is explicitly implemented more than once.* - [**CS8705**](#ambiguous-and-conflicting-implementations): *Interface member does not have a most specific implementation. Neither member is most specific.* - [**CS8854**](#return-types-and-signatures): *Member does not implement interface member.* - [**CS9333**](#return-types-and-signatures): *Parameter type must match implemented member.* @@ -205,11 +208,13 @@ For more information, see [Interfaces](../../fundamentals/types/interfaces.md), The following errors occur when the compiler can't determine which interface implementation to use: - **CS0473**: *Explicit interface implementation 'method name' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead.* +- **CS8646**: *'member' is explicitly implemented more than once.* - **CS8705**: *Interface member 'member' does not have a most specific implementation. Neither is most specific.* You can correct these errors using the following techniques: - Eliminate the explicit interface implementation and instead use a single implicit public implementation for both interface methods (**CS0473**). When a generic method acquires the same signature as a non-generic method (such as when implementing `ITest` where both `TestMethod(int)` and `TestMethod(T)` become identical), the common language infrastructure metadata system can't unambiguously determine which interface member binds to which implementation slot, so using implicit implementation allows the single method to satisfy both interface requirements. +- Remove the duplicate explicit interface implementation for the same interface member (**CS8646**). A type can explicitly implement an interface member only once, so keep the implementation that should satisfy the interface contract and delete the duplicate declaration. - Provide an explicit implementation in the implementing class or struct that resolves the ambiguity between multiple default implementations (**CS8705**). This error typically occurs with diamond inheritance patterns where a class implements multiple interfaces that each provide default implementations for the same member. The compiler needs you to explicitly specify which implementation to use, or provide your own implementation. - Restructure the interface hierarchy to avoid diamond inheritance conflicts where multiple interfaces provide default implementations for the same member (**CS8705**). By redesigning the interface relationships or consolidating the default implementations into a single interface, you can eliminate the ambiguity that prevents the compiler from determining the most specific implementation. diff --git a/docs/csharp/language-reference/compiler-messages/local-function-errors.md b/docs/csharp/language-reference/compiler-messages/local-function-errors.md new file mode 100644 index 0000000000000..c77114e80fadb --- /dev/null +++ b/docs/csharp/language-reference/compiler-messages/local-function-errors.md @@ -0,0 +1,90 @@ +--- +title: "Resolve errors and warnings related to local functions" +description: "This article helps you diagnose and correct compiler errors and warnings related to local functions" +f1_keywords: + - "CS8108" + - "CS8112" + - "CS8321" + - "CS8421" + - "CS8422" +helpviewer_keywords: + - "CS8108" + - "CS8112" + - "CS8321" + - "CS8421" + - "CS8422" +ms.date: 07/16/2026 +ai-usage: ai-assisted +--- +# Resolve errors and warnings related to local functions + +This article covers the following compiler errors and warnings: + + +- [**CS8108**](#params-parameters-and-dynamic-arguments): *Cannot pass argument with dynamic type to params parameter 'parameter' of local function 'method'.* +- [**CS8112**](#local-function-bodies): *Local function 'method' must declare a body because it is not marked 'static extern'.* +- [**CS8321**](#unused-local-functions): *The local function 'method' is declared but never used* +- [**CS8421**](#static-local-functions-cant-capture-state): *A static local function cannot contain a reference to 'variable'.* +- [**CS8422**](#static-local-functions-cant-capture-state): *A static local function cannot contain a reference to 'this' or 'base'.* + +[Local functions](../../programming-guide/classes-and-structs/local-functions.md) were added in C# 7.0. They let you declare helper methods inside another member. The diagnostics in this article cover local function declarations, calls, usage, and the extra capture restrictions for `static` local functions. + +## Local function bodies + +- **CS8112**: *Local function 'method' must declare a body because it is not marked 'static extern'.* + +A local function declaration must include a body unless the local function is declared `static extern`. Add a block body or an expression body to the local function. If the implementation is supplied externally, mark the local function `static extern` and ensure the declaration follows the rules for external methods. + +## Params parameters and dynamic arguments + +- **CS8108**: *Cannot pass argument with dynamic type to params parameter 'parameter' of local function 'method'.* + +A local function call can't pass a `dynamic` argument to a `params` parameter. Convert the value to the element type or array type expected by the `params` parameter before the call. You can also store the values in an explicitly typed array and pass that array to the local function. + +## Unused local functions + +- **CS8321**: *The local function 'method' is declared but never used* + +The compiler reports this warning when you declare a local function but no reachable code calls it. Remove the unused local function, or call it from the enclosing member. If you intend to use the local function in a future change, keep it out of the source until it's needed. + +## Static local functions can't capture state + +- **CS8421**: *A static local function cannot contain a reference to 'variable'.* +- **CS8422**: *A static local function cannot contain a reference to 'this' or 'base'.* + +A [`static` local function](../../programming-guide/classes-and-structs/local-functions.md) can't capture state from the enclosing scope. It can't reference enclosing local variables, parameters, instance members through `this`, or `this` itself. Pass each value the local function needs as a parameter (**CS8421**, **CS8422**). If the local function must capture variables or instance state from the enclosing scope, remove the `static` modifier. + +The following example shows references that cause **CS8422**: + +```csharp +public class C +{ + private int counter = 1; + + public void IncreaseCounter() + { + static void LocalFunc(int addition) + { + this.counter += addition; // CS8422 + base.ToString(); // CS8422 + + counter += addition; // CS8422: implicit this + ToString(); // CS8422: implicit base + } + + LocalFunc(10); + } +} +``` + +To fix **CS8422**, pass the required instance data to the local function, move the helper outside the instance context, or remove `static` when the local function must access instance state. + +## Related diagnostics + +- For more information about local functions in expression trees, see [Some expressions are prohibited in expression trees](expression-tree-restrictions.md) in C# compiler messages. +- For more information about local functions with generic type parameters, see [Resolve errors and warnings related to generic type parameters and type arguments](generic-type-parameters-errors.md) in C# compiler messages. +- For more information about attributes on local functions, see [Resolve errors and warnings that involve attribute declaration and attribute use in your code](attribute-usage-errors.md) in C# compiler messages. +- For more information about captured variables in anonymous functions, see [Lambda expression errors and warnings](lambda-expression-errors.md) in C# compiler messages. +- For more information about captures in constructors and primary constructors, see [Resolve errors related to constructor declarations and module initializers](constructor-errors.md) in C# compiler messages. diff --git a/docs/csharp/language-reference/compiler-messages/nullable-warnings.md b/docs/csharp/language-reference/compiler-messages/nullable-warnings.md index 45cfcd9761ae4..82bf46458e754 100644 --- a/docs/csharp/language-reference/compiler-messages/nullable-warnings.md +++ b/docs/csharp/language-reference/compiler-messages/nullable-warnings.md @@ -41,8 +41,11 @@ f1_keywords: - "CS8643" # WRN_NullabilityMismatchInExplicitlyImplementedInterface: Nullability of reference types in explicit interface specifier doesn't match interface implemented by the type. - "CS8644" # WRN_NullabilityMismatchInInterfaceImplementedByBase: '{0}' does not implement interface member '{1}'. Nullability of reference types in interface implemented by the base type doesn't match. - "CS8645" # WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList: '{0}' is already listed in the interface list on type '{1}' with different nullability of reference types. + - "CS8650" + - "CS8651" - "CS8655" # WRN_SwitchExpressionNotExhaustiveForNull: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '{0}' is not covered. - "CS8667" # WRN_NullabilityMismatchInConstraintsOnPartialImplementation: Partial method declarations of '{0}' have inconsistent nullability in constraints for type parameter '{1}' + - "CS8669" - "CS8670" # WRN_NullReferenceInitializer: Object or collection initializer implicitly dereferences possibly null member '{0}'. - "CS8714" # WRN_NullabilityMismatchInTypeParameterNotNullConstraint: The type '{2}' cannot be used as type parameter '{1}' in the generic type or method '{0}'. Nullability of type argument '{2}' doesn't match 'notnull' constraint. - "CS8762" # WRN_ParameterConditionallyDisallowsNull: Parameter '{0}' must have a non-null value when exiting with '{1}'. @@ -98,13 +101,16 @@ helpviewer_keywords: - "CS8634" - "CS8636" - "CS8637" - - "CS8668" - "CS8639" - "CS8643" - "CS8644" - "CS8645" + - "CS8650" + - "CS8651" - "CS8655" - "CS8667" + - "CS8668" + - "CS8669" - "CS8670" - "CS8714" - "CS8762" @@ -124,7 +130,8 @@ helpviewer_keywords: - "CS8824" - "CS8825" - "CS8847" -ms.date: 02/20/2025 +ms.date: 07/16/2026 +ai-usage: ai-assisted --- # Nullable reference type warnings @@ -173,8 +180,11 @@ This article covers the following compiler warnings: - [**CS8643**](#mismatch-in-nullability-declaration) - *Nullability of reference types in explicit interface specifier doesn't match interface implemented by the type.* - [**CS8644**](#mismatch-in-nullability-declaration) - *Type does not implement interface member. Nullability of reference types in interface implemented by the base type doesn't match.* - [**CS8645**](#mismatch-in-nullability-declaration) - *Member is already listed in the interface list on type with different nullability of reference types.* +- [**CS8650**](#incorrect-annotation-syntax) - *It is not legal to use nullable reference type 'type?' in an is-type expression; use the underlying type 'type' instead.* +- [**CS8651**](#incorrect-annotation-syntax) - *It is not legal to use nullable reference type 'type?' in an as expression; use the underlying type 'type' instead.* - [**CS8655**](#exhaustive-switch-expression) - *The switch expression does not handle some null inputs (it is not exhaustive).* - [**CS8667**](#mismatch-in-nullability-declaration) - *Partial method declarations have inconsistent nullability in constraints for type parameter.* +- [**CS8669**](#configure-nullable-context) - *The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source.* - [**CS8670**](#possible-dereference-of-null) - *Object or collection initializer implicitly dereferences possibly null member.* - [**CS8714**](#mismatch-in-nullability-declaration) - *The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'notnull' constraint.* - [**CS8762**](#nonnullable-reference-not-initialized) - *Parameter must have a non-null value when exiting.* @@ -216,6 +226,7 @@ The following warnings indicate that you haven't set the nullable context correc - **CS8636** - *Invalid option for `/nullable`; must be `disable`, `enable`, `warnings` or `annotations`* - **CS8637** - *Expected `enable`, `disable`, or `restore`* - **CS8668** - *Expected `warnings`, `annotations`, or end of directive* +- **CS8669** - *The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source.* To set the nullable context correctly, you have two options: @@ -235,9 +246,11 @@ To set the nullable context correctly, you have two options: The nullable context has two independent flags that control different aspects: -- **Annotation flag**: Controls whether you can use `?` to declare nullable reference types and `!` to surpress individual warnings. +- **Annotation flag**: Controls whether you can use `?` to declare nullable reference types and `!` to suppress individual warnings. - **Warning flag**: Controls whether the compiler emits nullability warnings +In generated code, add an explicit `#nullable` directive to the generated source before you use nullable annotations (**CS8669**). Project-level nullable settings might not apply to generated source files. + For detailed information about nullable contexts and migration strategies, see: - [Nullable reference types](../builtin-types/nullable-reference-types.md) @@ -251,6 +264,8 @@ These errors and warnings indicate that usage of the `!` or `?` annotation is in - **CS8623** - *Explicit application of `System.Runtime.CompilerServices.NullableAttribute` is not allowed.* - **CS8628** - *Cannot use a nullable reference type in object creation.* - **CS8639** - *The typeof operator cannot be used on a nullable reference type* +- **CS8650** - *It is not legal to use nullable reference type 'type?' in an is-type expression; use the underlying type 'type' instead.* +- **CS8651** - *It is not legal to use nullable reference type 'type?' in an as expression; use the underlying type 'type' instead.* The `?` annotation in a declaration indicates that the variable might be null. It doesn't indicate a different runtime type. Both the following declarations are the same runtime type: @@ -264,7 +279,7 @@ The `?` is a hint to the compiler on the expectation for null values. The `!` annotation on an expression indicates that you know the expression is safe and should be assumed to be not null. - You must use these annotations, not the in your code. -- Because the `?` is an annotation, not a type, you can't use it with [`typeof`](../operators/type-testing-and-cast.md#the-typeof-operator), or [`new`](../operators/new-operator.md) expressions. +- Because the `?` is an annotation, not a type, you can't use it with [`typeof`](../operators/type-testing-and-cast.md#the-typeof-operator), [`new`](../operators/new-operator.md), [`is`](../operators/type-testing-and-cast.md#the-is-operator), or [`as`](../operators/type-testing-and-cast.md#the-as-operator) expressions. Use the underlying nonnullable reference type in `is` and `as` expressions because nullable annotations have no runtime representation (**CS8650**, **CS8651**). - The `!` operator can't be applied to a variable expression or a method group. - The `!` operator can't be applied to the left of a member access operator, such as `obj.Field!.Method()`. diff --git a/docs/csharp/language-reference/compiler-messages/parsing-errors.md b/docs/csharp/language-reference/compiler-messages/parsing-errors.md new file mode 100644 index 0000000000000..c02c814c85af0 --- /dev/null +++ b/docs/csharp/language-reference/compiler-messages/parsing-errors.md @@ -0,0 +1,32 @@ +--- +title: "Resolve errors related to parsing C# code" +description: "This article helps you diagnose and correct compiler errors related to parsing C# code" +f1_keywords: + - "CS8635" + - "CS8641" +helpviewer_keywords: + - "CS8635" + - "CS8641" +ms.date: 07/16/2026 +ai-usage: ai-assisted +--- +# Resolve errors related to parsing C# code + +This article covers lexer and parser-stage diagnostics for unexpected character sequences, unexpected tokens, and malformed statement structure. It isn't a general syntax-error catalog. + +This article covers the following compiler errors: + + +- [**CS8635**](#unexpected-parser-stage-tokens-and-statements): *Unexpected character sequence '...'* +- [**CS8641**](#unexpected-parser-stage-tokens-and-statements): *'else' cannot start a statement.* + +## Unexpected parser-stage tokens and statements + +- **CS8635**: *Unexpected character sequence '...'* +- **CS8641**: *'else' cannot start a statement.* + +The lexer and parser require token sequences that form valid C# statements. Remove a stray `...` sequence (**CS8635**). If you intended a range expression, use two dots (`..`). If the dots are part of other text, put that text in a string literal or comment. + +An `else` clause must immediately follow the matching [`if` statement](../statements/selection-statements.md#the-if-statement) (**CS8641**). Restructure the code so `else` doesn't begin a statement. Add the missing `if`, remove the unmatched `else`, or move intervening statements inside the intended `if` or `else` block. diff --git a/docs/csharp/language-reference/compiler-messages/readonly-struct-errors.md b/docs/csharp/language-reference/compiler-messages/readonly-struct-errors.md new file mode 100644 index 0000000000000..8cbf00da0ee72 --- /dev/null +++ b/docs/csharp/language-reference/compiler-messages/readonly-struct-errors.md @@ -0,0 +1,54 @@ +--- +title: "Resolve errors and warnings related to readonly structs and members" +description: "This article helps you diagnose and correct compiler errors and warnings related to readonly structs and members" +f1_keywords: + - "CS8340" + - "CS8342" + - "CS8656" + - "CS8662" +helpviewer_keywords: + - "CS8340" + - "CS8342" + - "CS8656" + - "CS8662" +ms.date: 07/16/2026 +ai-usage: ai-assisted +--- +# Resolve errors and warnings related to readonly structs and members + +This article covers the following compiler errors and warnings: + + +- [**CS8340**](#readonly-struct-declaration-rules): *Instance fields of readonly structs must be readonly.* +- [**CS8342**](#readonly-struct-declaration-rules): *Field-like events are not allowed in readonly structs.* +- [**CS8656**](#readonly-struct-member-restrictions): *Call to non-readonly member 'member' from a 'readonly' member results in an implicit copy of 'type'.* +- [**CS8662**](#readonly-struct-member-restrictions): *Field-like event 'event' cannot be 'readonly'.* + +A [`readonly struct`](../builtin-types/struct.md#readonly-struct) declaration promises that instance state doesn't mutate. A [`readonly` instance member](../builtin-types/struct.md#readonly-instance-members) promises that the member doesn't mutate the current instance. The diagnostics in this article cover both declarations and member bodies. + +## Readonly struct declaration rules + +- **CS8340**: *Instance fields of readonly structs must be readonly.* +- **CS8342**: *Field-like events are not allowed in readonly structs.* + +Every instance field declared in a `readonly struct` must also be `readonly` (**CS8340**). Add the `readonly` modifier to each instance field, convert mutable fields to immutable state, or remove `readonly` from the struct declaration when instances must mutate. + +Field-like events aren't allowed in a `readonly struct` (**CS8342**) because the compiler-generated backing field is mutable. Use a manually implemented event with explicit `add` and `remove` accessors, or remove `readonly` from the struct declaration. + +## Readonly struct member restrictions + +- **CS8656**: *Call to non-readonly member 'member' from a 'readonly' member results in an implicit copy of 'type'.* +- **CS8662**: *Field-like event 'event' cannot be 'readonly'.* + +A `readonly` instance member of a struct can't mutate `this`. When a `readonly` member calls a non-`readonly` member, the compiler copies `this` before the call so the non-`readonly` member can't modify the original instance. Mark the called member `readonly` when it doesn't modify instance state, or call only members that are already `readonly` (**CS8656**). If the called member must mutate instance state, remove `readonly` from the caller. + +Field-like events can't be marked `readonly` (**CS8662**). Remove the `readonly` modifier from the event, or implement the event manually with `add` and `remove` accessors that follow the readonly rules for the containing struct. + +## Related diagnostics + +- For more information about auto-implemented properties in readonly structs, see [Compiler Errors on property declarations](property-declaration-errors.md) in C# compiler messages. That article includes **CS8341**, the third readonly struct declaration rule. +- For more information about readonly properties, indexers, and accessors, see [Compiler Errors on property declarations](property-declaration-errors.md) in C# compiler messages. +- For more information about readonly partial declarations, see [Compiler Errors on partial type and member declarations](partial-declarations.md) in C# compiler messages. +- For more information about readonly types and primary constructors, see [Resolve errors related to constructor declarations and module initializers](constructor-errors.md) in C# compiler messages. diff --git a/docs/csharp/language-reference/toc.yml b/docs/csharp/language-reference/toc.yml index 1654d4c4eb8df..da7fb16999452 100644 --- a/docs/csharp/language-reference/toc.yml +++ b/docs/csharp/language-reference/toc.yml @@ -484,13 +484,18 @@ items: CS1024, CS1025, CS1027, CS1028, CS1029, CS1030, CS1032, CS1038, CS1040, CS1517, CS1560, CS1576, CS1578, CS1633, CS1634, CS1635, CS1691, CS1692, CS1694, CS1695, CS1696, CS1709, CS9297, CS9298, CS9299, CS9314 + - name: Parsing C# code + href: ./compiler-messages/parsing-errors.md + displayName: > + parser, lexer, unexpected character, else statement, + CS8635, CS8641 - name: Attribute declaration and usage href: ./compiler-messages/attribute-usage-errors.md displayName: > CS0181, CS0243, CS0404, CS0415, CS0416, CS0447, CS0577, CS0578, CS0579, CS0582, CS0592, CS0609, CS0616, CS0625, CS0629, CS0636, CS0637, CS0641, CS0646, CS0647, CS0653, CS0657, CS0658, CS0668, CS0685, CS0735, CS0739, CS1608, CS1614, CS1618, - CS1667, CS1689, CS7014, CS7046, CS7047, CS7067, CS8783, CS8959, CS8960, CS8961, + CS1667, CS1689, CS7014, CS7046, CS7047, CS7067, CS8423, CS8783, CS8959, CS8960, CS8961, CS8962, CS8963, CS8968, CS8970, CS9331 - name: Feature or version missing href: ./compiler-messages/feature-version-errors.md @@ -546,6 +551,11 @@ items: CS8852, CS8853, CS8855, CS8856, CS8903, CS9029, CS9030, CS9031, CS9032, CS9033, CS9034, CS9035, CS9036, CS9037, CS9038, CS9039, CS9040, CS9042, CS9045, CS9258, CS9263, CS9264, CS9266, CS9273 + - name: Readonly structs and members + href: ./compiler-messages/readonly-struct-errors.md + displayName: > + readonly struct, readonly member, readonly event, implicit copy, + CS8340, CS8342, CS8656, CS8662 - name: Operator declarations href: ./compiler-messages/overloaded-operator-errors.md displayName: > @@ -556,6 +566,11 @@ items: CS0562, CS0563, CS0564, CS0567, CS0590, CS0594, CS0652, CS0659, CS0660, CS0661, CS0715, CS1021, CS1037, CS1553, CS8761, CS8778, CS8973, CS9023, CS9024, CS9025, CS9027, CS9308, CS9310, CS9311, CS9312, CS9313, CS9340, CS9341, CS9342 + - name: Indexer and element access + href: ./compiler-messages/indexer-access-errors.md + displayName: > + index, range, Index, Range, indexer, element access, accessor, indexed property, + CS0021, CS0154, CS0271, CS0272, CS0856, CS0857, CS1545, CS1546, CS8428, CS8429 - name: Parameter / argument mismatch href: ./compiler-messages/parameter-argument-mismatch.md displayName: > @@ -593,7 +608,7 @@ items: interface, CS0071, CS0106, CS0277, CS0425, CS0460, CS0470, CS0473, CS0531, CS0535, CS0538, CS0539, CS0540, CS0541, CS0550, CS0551, CS0630, CS0686, CS0736, CS0737, CS0738, - CS8705, CS8707, CS8711, CS8854, CS9333, CS9334 + CS8646, CS8705, CS8707, CS8711, CS8854, CS9333, CS9334 - name: Reference parameters href: ./compiler-messages/ref-modifiers-errors.md displayName: > @@ -657,9 +672,10 @@ items: CS8597, CS8598, CS8600, CS8601, CS8602, CS8604, CS8605, CS8607, CS8608, CS8609, CS8610, CS8611, CS8612, CS8613, CS8614, CS8615, CS8616, CS8617, CS8618, CS8619, CS8620, CS8621, CS8622, CS8623, CS8624, CS8625, CS8628, CS8629, CS8631, CS8632, - CS8634, CS8636, CS8637, CS8639, CS8655, CS8633, CS8643, CS8644, CS8645, CS8762, - CS8763, CS8764, CS8765, CS8766, CS8667, CS8768, CS8670, CS8714, CS8767, CS8769, - CS8770, CS8774, CS8776, CS8775, CS8777, CS8819, CS8824, CS8825, CS8847 + CS8633, CS8634, CS8636, CS8637, CS8639, CS8643, CS8644, CS8645, CS8650, CS8651, + CS8655, CS8667, CS8669, CS8670, CS8714, CS8762, CS8763, CS8764, CS8765, CS8766, + CS8767, CS8768, CS8769, CS8770, CS8774, CS8775, CS8776, CS8777, CS8819, CS8824, + CS8825, CS8847 - name: Pattern matching warnings href: ./compiler-messages/pattern-matching-warnings.md displayName: > @@ -699,6 +715,11 @@ items: CS1688, CS1706, CS1731, CS1732, CS1764, CS1911, CS1989, CS3006, CS8030, CS8175, CS8820, CS8821, CS8916, CS8917, CS8934, CS8971, CS8972, CS8974, CS8975, CS9098, CS9099, CS9100, CS9236 + - name: Local functions + href: ./compiler-messages/local-function-errors.md + displayName: > + local function, static local function, capture, enclosing scope, params, + CS8108, CS8112, CS8321, CS8421, CS8422 - name: Delegate and function pointer declarations href: ./compiler-messages/delegate-function-pointer-diagnostics.md displayName: > @@ -1339,8 +1360,6 @@ items: href: ../misc/cs1542.md - name: CS1545 href: ../misc/cs1545.md - - name: CS1546 - href: ./compiler-messages/cs1546.md - name: CS1547 href: ../misc/cs1547.md - name: CS1548 @@ -1617,8 +1636,6 @@ items: href: ./compiler-messages/cs8354.md - name: CS8355 href: ./compiler-messages/cs8355.md - - name: CS8422 - href: ./compiler-messages/cs8422.md - name: CS9043 href: ./compiler-messages/cs9043.md - name: Level 1 warning messages diff --git a/docs/csharp/misc/sorry-we-don-t-have-specifics-on-this-csharp-error.md b/docs/csharp/misc/sorry-we-don-t-have-specifics-on-this-csharp-error.md index 4ea353a2ab2cd..8d1261d645c06 100644 --- a/docs/csharp/misc/sorry-we-don-t-have-specifics-on-this-csharp-error.md +++ b/docs/csharp/misc/sorry-we-don-t-have-specifics-on-this-csharp-error.md @@ -7,8 +7,6 @@ f1_keywords: - "CS0257" - "CS0595" - "CS0847" - - "CS0856" - - "CS0857" - "CS1066" - "CS1072" - "CS1073" @@ -158,9 +156,7 @@ f1_keywords: - "CS8104" - "CS8105" - "CS8106" - - "CS8108" - "CS8111" - - "CS8112" - "CS8113" # C# 7.0 diagnostics - "CS8115" @@ -200,13 +196,10 @@ f1_keywords: - "CS8310" - "CS8312" # C# 7.2 diagnostics - - "CS8321" - "CS8323" - "CS8328" - "CS8335" - "CS8336" - - "CS8340" - - "CS8342" - "CS8346" - "CS8347" - "CS8348" @@ -225,24 +218,12 @@ f1_keywords: - "CS8384" # C# 8.0 diagnostics ## Static local functions - - "CS8421" ## Attributes - - "CS8423" ## Index and range - - "CS8428" - - "CS8429" ## Can't parse syntax - - "CS8635" - - "CS8641" ## Default interface implementation - - "CS8646" ## Patterns - - "CS8650" - - "CS8651" ## Readonly struct members - - "CS8656" - - "CS8662" - - "CS8669" # Coming in C# 15 - "CS9343" # misc - "CS9347"