From fc64f8031901a113181afaba0e3e52466d1b3f3a Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Fri, 7 Nov 2025 12:05:11 -0500 Subject: [PATCH 1/6] Add errors for existing C# 14 themes Add all newly created diagnostics that map to existing consolidated error files. --- .../compiler-messages/array-declaration-errors.md | 3 +++ .../compiler-messages/extension-declarations.md | 3 +++ .../compiler-messages/feature-version-errors.md | 6 ++++++ .../compiler-messages/overloaded-operator-errors.md | 9 +++++++++ .../compiler-messages/pattern-matching-warnings.md | 4 +++- docs/csharp/language-reference/toc.yml | 11 ++++++----- ...ry-we-don-t-have-specifics-on-this-csharp-error.md | 3 --- 7 files changed, 30 insertions(+), 9 deletions(-) diff --git a/docs/csharp/language-reference/compiler-messages/array-declaration-errors.md b/docs/csharp/language-reference/compiler-messages/array-declaration-errors.md index 211d07ae2b64f..acfe15b613fe0 100644 --- a/docs/csharp/language-reference/compiler-messages/array-declaration-errors.md +++ b/docs/csharp/language-reference/compiler-messages/array-declaration-errors.md @@ -42,6 +42,7 @@ f1_keywords: - "CS9214" - "CS9215" - "CS9222" + - "CS9332" helpviewer_keywords: - "CS0022" - "CS0178" @@ -83,6 +84,7 @@ helpviewer_keywords: - "CS9214" - "CS9215" - "CS9222" + - "CS9332" ms.date: 11/02/2023 --- # Resolve errors and warnings in array and collection declarations and initialization expressions @@ -125,6 +127,7 @@ That's by design. The text closely matches the text of the compiler error / warn - [**CS9214**](#invalid-collection-initializer): *Collection expression type must have an applicable constructor that can be called with no arguments.* - [**CS9215**](#invalid-collection-initializer): *Collection expression type 'type' must have an instance or extension method 'Add' that can be called with a single argument.* - [**CS9222**](#invalid-collection-initializer): *Collection initializer results in an infinite chain of instantiations of collection 'type'.* +- [**CS9332**](#invalid-collection-initializer): *Cannot use '..' spread operator in the filter expression of a catch clause* In addition, the following warnings are covered in this article: diff --git a/docs/csharp/language-reference/compiler-messages/extension-declarations.md b/docs/csharp/language-reference/compiler-messages/extension-declarations.md index 6e0b9bb66c72a..3a27bb5cd09d3 100644 --- a/docs/csharp/language-reference/compiler-messages/extension-declarations.md +++ b/docs/csharp/language-reference/compiler-messages/extension-declarations.md @@ -44,6 +44,7 @@ f1_keywords: - "CS9323" - "CS9326" - "CS9329" + - "CS9339" helpviewer_keywords: - "CS1100" - "CS1101" @@ -88,6 +89,7 @@ helpviewer_keywords: - "CS9323" - "CS9326" - "CS9329" + - "CS9339" --- # Errors and warnings related to extension methods declared with `this` parameters or `extension` blocks @@ -134,6 +136,7 @@ helpviewer_keywords: - [**CS9323**](#errors-related-to-extension-block-declarations): *Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class.* - [**CS9326**](#errors-related-to-extension-block-declarations): *'`name`': extension member names cannot be the same as their extended type.* - [**CS9329**](#errors-related-to-extension-block-declarations): *This extension block collides with another extension block. They result in conflicting content-based type names in metadata.* +- [**CS9339**](#errors-related-to-extension-block-declarations): *The extension resolution is ambiguous between the following members.* ## Common errors on extension declarations diff --git a/docs/csharp/language-reference/compiler-messages/feature-version-errors.md b/docs/csharp/language-reference/compiler-messages/feature-version-errors.md index 2f2ace8407605..d3eaae9a09ee4 100644 --- a/docs/csharp/language-reference/compiler-messages/feature-version-errors.md +++ b/docs/csharp/language-reference/compiler-messages/feature-version-errors.md @@ -58,6 +58,8 @@ f1_keywords: - "CS9268" - "CS9269" - "CS9271" + - "CS9327" + - "CS9328" helpviewer_keywords: - "CS0171" - "CS0188" @@ -115,6 +117,8 @@ helpviewer_keywords: - "CS9268" - "CS9269" - "CS9271" + - "CS9327" + - "CS9328" ms.date: 05/23/2025 --- # Resolve warnings related to language features and versions @@ -161,6 +165,8 @@ That's be design. The text closely matches the text of the compiler error / warn - **CS9268**: *Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.* - **CS9269**: *UnscopedRefAttribute is only valid in C# 11 or later or when targeting net7.0 or later.* - [**CS9271**](#implementation-specific-attributes): *The type '`Microsoft.CodeAnalysis.EmbeddedAttribute`' must be non-generic, internal, sealed, non-static, have a parameterless constructor, inherit from System.Attribute, and be able to be applied to any type.* +- **CS9327**: *Feature is not available in C# 14.0. Use newer language version.* +- **CS9328**: *Method uses a feature that is not supported by runtime async currently.* In addition, the following errors and warnings relate to struct initialization changes in recent versions: diff --git a/docs/csharp/language-reference/compiler-messages/overloaded-operator-errors.md b/docs/csharp/language-reference/compiler-messages/overloaded-operator-errors.md index 9458f1b54d92d..e124b86baac49 100644 --- a/docs/csharp/language-reference/compiler-messages/overloaded-operator-errors.md +++ b/docs/csharp/language-reference/compiler-messages/overloaded-operator-errors.md @@ -37,6 +37,9 @@ f1_keywords: - "CS9311" - "CS9312" - "CS9313" + - "CS9340" + - "CS9341" + - "CS9342" helpviewer_keywords: - "CS0056" - "CS0057" @@ -73,6 +76,9 @@ helpviewer_keywords: - "CS9311" - "CS9312" - "CS9313" + - "CS9340" + - "CS9341" + - "CS9342" ms.date: 10/15/2025 ai-usage: ai-assisted --- @@ -118,6 +124,9 @@ That's by design. The text closely matches the text of the compiler error / warn - [**CS9311**](#interface-and-inheritance-requirements): *Type does not implement interface member. The type cannot implement member because one of them is not an operator.* - [**CS9312**](#interface-and-inheritance-requirements): *Type cannot override inherited member because one of them is not an operator.* - [**CS9313**](#interface-and-inheritance-requirements): *Overloaded compound assignment operator takes one parameter.* +- [**CS9340**](#operator-signature-requirements): *Operator cannot be applied to operands. The closest inapplicable candidate is shown.* +- [**CS9341**](#operator-signature-requirements): *Operator cannot be applied to operand. The closest inapplicable candidate is shown.* +- [**CS9342**](#operator-signature-requirements): *Operator resolution is ambiguous between the following members.* The following sections provide examples of common issues and how to fix them. diff --git a/docs/csharp/language-reference/compiler-messages/pattern-matching-warnings.md b/docs/csharp/language-reference/compiler-messages/pattern-matching-warnings.md index 2c0e6f799ad52..009dc09a51a05 100644 --- a/docs/csharp/language-reference/compiler-messages/pattern-matching-warnings.md +++ b/docs/csharp/language-reference/compiler-messages/pattern-matching-warnings.md @@ -6,11 +6,13 @@ f1_keywords: - "CS9134" - "CS9135" - "CS9335" + - "CS9336" - "CS9337" helpviewer_keywords: - "CS8509" - "CS9134" - "CS9335" + - "CS9336" - "CS9337" ms.date: 10/16/2025 --- @@ -20,7 +22,7 @@ The compiler generates the following errors for invalid pattern match expression - **CS9134**: *A switch expression arm does not begin with a 'case' keyword.* - **CS9135**: *A constant value of type is expected* -- **CS9335**: *The pattern is redundant.* +- **CS9335, CS9336**: *The pattern is redundant.* - **CS9337**: *The pattern is too complex to analyze for redundancy.* The compiler generates the following warnings for incomplete pattern matching expressions: diff --git a/docs/csharp/language-reference/toc.yml b/docs/csharp/language-reference/toc.yml index 94decd6cadc06..ccba45bd2a50e 100644 --- a/docs/csharp/language-reference/toc.yml +++ b/docs/csharp/language-reference/toc.yml @@ -474,7 +474,7 @@ items: CS8320, CS8370, CS8371, CS8400, CS8401, CS8511, CS8627, CS8630, CS8652, CS8703, CS8704, CS8706, CS8773, CS8912, CS8919, CS8929, CS8936, CS8957, CS8967, CS9014, CS9015, CS9016, CS9017, CS9058, CS9064, CS9103, CS9171, CS9194, CS9202, CS9204, - CS9240, CS9260, CS9268, CS9269, CS9271 + CS9240, CS9260, CS9268, CS9269, CS9271, CS9327, CS9328 - name: Assembly references href: ./compiler-messages/assembly-references.md displayName: > @@ -496,7 +496,7 @@ items: CS0056, CS0057, CS0215, CS0216, CS0217, CS0218, CS0448, CS0552, CS0553, CS0554, CS0555, CS0556, CS0557, CS0558, CS0559, CS0562, CS0563, CS0564, CS0567, CS0590, CS0660, CS0661, CS0715, CS1037, CS1553, CS1554, CS8930, CS8931, CS9023, CS9024, - CS9025, CS9308, CS9310, CS9311, CS9312, CS9313 + CS9025, CS9308, CS9310, CS9311, CS9312, CS9313, CS9340, CS9341, CS9342 - name: Parameter / argument mismatch href: ./compiler-messages/parameter-argument-mismatch.md displayName: > @@ -533,7 +533,7 @@ items: CS1743, CS9281, CS9282, CS9283, CS9284, CS9285, CS9287, CS9288, CS9289, CS9290, CS9292, CS9293, CS9295, CS9300, CS9301, CS9302, CS9303, CS9304, CS9305, CS9306, CS9309, CS9316, CS9317, CS9318, CS9319, CS9320, CS9321, CS9322, CS9323, CS9326, - CS9329 + CS9329, CS9339 - name: Partial declarations href: ./compiler-messages/partial-declarations.md displayName: > @@ -560,7 +560,7 @@ items: CS8770, CS8774, CS8776, CS8775, CS8777, CS8819, CS8824, CS8825, CS8847 - name: Pattern matching warnings href: ./compiler-messages/pattern-matching-warnings.md - displayName: CS8509, CS9134, CS9135, CS9335, CS9337 + displayName: CS8509, CS9134, CS9135, CS9335, CS9336, CS9337 - name: String literal declarations href: ./compiler-messages/string-literal.md displayName: > @@ -573,7 +573,8 @@ items: CS0022, CS0178, CS0248, CS0251, CS0270, CS0611, CS0623, CS0650, CS0719, CS0747, CS0820, CS0826, CS0846, CS1062, CS1063, CS1064, CS1552, CS1586, CS1920, CS1921, CS1925, CS1950, CS1954, CS3007, CS3016, CS9174, CS9176, CS9185, CS9186, CS9187, - CS9188, CS9203, CS9208, CS9209, CS9210, CS9212, CS9213, CS9214, CS9215, CS9222 + CS9188, CS9203, CS9208, CS9209, CS9210, CS9212, CS9213, CS9214, CS9215, CS9222, + CS9332 - name: Inline arrays href: ./compiler-messages/inline-array-errors.md displayName: > 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 e33a9a15c0a6d..9fe1611f0a880 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 @@ -548,11 +548,8 @@ f1_keywords: - "CS9096" - "CS9097" # C# 14 errors begin here - - "CS9327" - - "CS9328" - "CS9330" - "CS9331" - - "CS9332" - "CS9333" - "CS9334" - "CS9338" From 3a8dfc1c3e6aa56601fb087c290f328eadecb6cd Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Fri, 7 Nov 2025 12:51:34 -0500 Subject: [PATCH 2/6] Update docs/csharp/language-reference/compiler-messages/array-declaration-errors.md Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .../compiler-messages/array-declaration-errors.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/csharp/language-reference/compiler-messages/array-declaration-errors.md b/docs/csharp/language-reference/compiler-messages/array-declaration-errors.md index acfe15b613fe0..1aa453ecbfd82 100644 --- a/docs/csharp/language-reference/compiler-messages/array-declaration-errors.md +++ b/docs/csharp/language-reference/compiler-messages/array-declaration-errors.md @@ -127,7 +127,7 @@ That's by design. The text closely matches the text of the compiler error / warn - [**CS9214**](#invalid-collection-initializer): *Collection expression type must have an applicable constructor that can be called with no arguments.* - [**CS9215**](#invalid-collection-initializer): *Collection expression type 'type' must have an instance or extension method 'Add' that can be called with a single argument.* - [**CS9222**](#invalid-collection-initializer): *Collection initializer results in an infinite chain of instantiations of collection 'type'.* -- [**CS9332**](#invalid-collection-initializer): *Cannot use '..' spread operator in the filter expression of a catch clause* +- [**CS9332**](#invalid-collection-initializer): *Cannot use '..' spread operator in the filter expression of a catch clause.* In addition, the following warnings are covered in this article: From f32330a33c7d4ce9b248ce9856a5044690f753e9 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Fri, 7 Nov 2025 13:54:59 -0500 Subject: [PATCH 3/6] Edit pass on array errors. After adding the final C# 14 updates, perform an edit pass to match the current format. --- .../array-declaration-errors.md | 194 +++++++++++------- 1 file changed, 122 insertions(+), 72 deletions(-) diff --git a/docs/csharp/language-reference/compiler-messages/array-declaration-errors.md b/docs/csharp/language-reference/compiler-messages/array-declaration-errors.md index 1aa453ecbfd82..b4ee7126f28b7 100644 --- a/docs/csharp/language-reference/compiler-messages/array-declaration-errors.md +++ b/docs/csharp/language-reference/compiler-messages/array-declaration-errors.md @@ -85,7 +85,8 @@ helpviewer_keywords: - "CS9215" - "CS9222" - "CS9332" -ms.date: 11/02/2023 +ms.date: 11/07/2025 +ai-usage: ai-assisted --- # Resolve errors and warnings in array and collection declarations and initialization expressions @@ -138,75 +139,62 @@ In addition, the following warnings are covered in this article: - [**CS0251**](#invalid-array-element-access): *Indexing an array with a negative index (array indices always start at zero)* - [**CS9208**](#invalid-collection-initializer): *Collection expression may incur unexpected heap allocations. Consider explicitly creating an array, then converting to the final type to make the allocation explicit.* - [**CS9209**](#invalid-collection-initializer): *Collection expression may incur unexpected heap allocations due to use of '`..`' spreads. Consider explicitly creating an array, then converting to the final type to make the allocation explicit.* +- [**CS9332**](#invalid-collection-initializer): *Cannot use '..' spread operator in the filter expression of a catch clause.* -You can learn more about arrays, collection initializers and collection expressions in the following articles: +## Invalid array element access -- [Arrays](../builtin-types/arrays.md) -- [Object and Collection Initializers](../../programming-guide/classes-and-structs/object-and-collection-initializers.md) -- [Collection expressions](../operators/collection-expressions.md). +- **CS0022**: *Wrong number of indices inside [], expected 'number'* +- **CS0251**: *Indexing an array with a negative index (array indices always start at zero)* -## Invalid collection initializer +To access array elements correctly, follow these indexing rules. For more information, see [Arrays](../builtin-types/arrays.md). -The following errors indicate that the code generated by the compiler for a collection initializer is invalid: +- Specify the same number of indices as declared dimensions (**CS0022**). A one-dimensional array needs one index, a three-dimensional array needs three indices. +- Use only non-negative integers for array indices (**CS0251**). Array indices always start at zero. + +## Invalid collection initializer - **CS0747**: *Invalid initializer member declarator.* -- **CS1063**: *The best overloaded Add method for the collection initializer element is obsolete.* - **CS1920**: *Element initializer cannot be empty.* - **CS1921**: *The best overloaded method match has wrong signature for the initializer element. The initializable `Add` must be an accessible instance method.* +- **CS1922**: *Cannot initialize type 'type' with a collection initializer because 'type' doesn't implement 'System.Collections.IEnumerable'.* +- **CS1925**: *Cannot initialize object of type 'type' with a collection initializer.* +- **CS1927**: *Warning: Ignoring /win32manifest for module because it only applies to assemblies* - **CS1950**: *The best overloaded Add method for the collection initializer has some invalid arguments.* - **CS1954**: *The best overloaded method match for the collection initializer element cannot be used. Collection initializer '`Add`' methods cannot have `ref` or `out` parameters.* - **CS9174**: *Cannot initialize type with a collection literal because the type is not constructible.* - **CS9176**: *There is no target type for the collection literal.* - **CS9203**: *A collection expression of this type cannot be used in this context because it may be exposed outside of the current scope.* -- **CS9210**: *This version of cannot be used with collection expressions.* -- **CS9212**: *Spread operator '`..`' cannot operate on variables of type 'type' because 'type' does not contain a public instance or extension definition for 'member'.* +- **CS9210**: *This version of can't be used with collection expressions.* +- **CS9212**: *Spread operator '`..`' cannot operate on variables of type 'type' because 'type' doesn't contain a public instance or extension definition for 'member'.* - **CS9213**: *Collection expression target 'type' has no element type.* - **CS9214**: *Collection expression type must have an applicable constructor that can be called with no arguments.* - **CS9215**: *Collection expression type 'type' must have an instance or extension method 'Add' that can be called with a single argument.* - **CS9222**: *Collection initializer results in an infinite chain of instantiations of collection 'type'.* +- **CS9332**: *Cannot use '..' spread operator in the filter expression of a catch clause.* -The compiler might also generate the following warning: +The compiler might also generate the following warnings: - **CS1062**: *The best overloaded Add method for the collection initializer element is obsolete.* +- **CS1063**: *The best overloaded Add method for the collection initializer element is obsolete.* - **CS1064**: *The best overloaded Add method for the collection initializer element is obsolete.* - **CS9208**: *Collection expression may incur unexpected heap allocations. Consider explicitly creating an array, then converting to the final type to make the allocation explicit.* - **CS9209**: *Collection expression may incur unexpected heap allocations due to use of '`..`' spreads. Consider explicitly creating an array, then converting to the final type to make the allocation explicit.* -The errors all indicate that the code generated by the compiler for a collection initializer is invalid. Check the following: - -- A collection initializer contains a sequence of elements. You can't mix setting properties on the collection instance with adding elements in the same initializer. -- A collection initializer that includes braces (`{` and `}`) can't be empty. -- The class must implement IEnumerable and have a public `Add` method. -- A conforming `Add` method must be accessible and take one parameter that is the same type as the collection elements. The parameter can't include the `ref` or `out` modifier. -- Overload resolution must pick one `Add` method as a better match. There can't be multiple matching methods that are equally good. -- Collection expressions can initialize explicitly typed variables of a collection type. If the variable isn't a collection or array type, or is implicitly typed (using `var`), a collection initializer can't be used. -- A `ref struct` type, like can't be initialized with a collection expression that may violate ref safety. -- A collection expression can't correctly initialize an using the current version. Use a different version of the runtime, or change the initialization expression. -- The spread operator (`..`) in **CS9212** requires the type to implement a suitable method (like `GetEnumerator`) to enumerate its elements. Ensure your type implements the required enumeration pattern or provides an extension method. -- **CS9213** occurs when the compiler can't determine what element type to use for the collection expression. This typically happens with custom collection types. Make sure your collection type properly exposes its element type through its type definition or implements appropriate collection interfaces. -- **CS9214** is generated when a collection expression tries to initialize a type that doesn't have a parameterless constructor. Collection expressions require a constructor that can be called with no arguments to create the instance before adding elements. -- **CS9215** happens when the collection type doesn't provide an `Add` method that accepts a single parameter of the element type. The `Add` method must be accessible (typically public) and accept exactly one argument that matches the collection's element type. -- **CS9222** indicates a circular dependency in collection initialization. This occurs when initializing a collection triggers the creation of another instance of the same collection type, which in turn requires initializing another instance, creating an infinite loop. Review your collection type's constructor and initialization logic to break the circular dependency. - -The warnings indicates that the collection expression, including any [spread elements](../operators/collection-expressions.md#spread-element) might allocate memory. Creating different storage and converting might be more efficient. - -## Invalid array initializer - -- **CS0623**: *Array initializers can only be used in a variable or field initializer. Try using a new expression instead.* -- **CS0846**: *A nested array initializer is expected* -- **CS1925**: *Cannot initialize object of type 'type' with a collection initializer.* - -These errors indicate that you've created an invalid initializer. The likely cause is unbalanced braces `{` and `}` around one or more elements or child arrays. Ensure that the initializing expression matches the number of arrays in a jagged array initialization, and that the braces are balanced. - -## Invalid array element access - -- **CS0022**: *Wrong number of indices inside [], expected 'number'* -- **CS0251**: *Indexing an array with a negative index (array indices always start at zero)* - -You access an element of an array by specifying the index for each axis declared in the array. The indices are between `[` and `]` after the array name. There are two rules for the array indices: - -1. You must specify the same number of indices as used in the array declaration. If the array has one dimension, you must specify one index. If the array has three dimensions, you must specify three indices. -1. All indices must be non-negative integers. +To create valid collection initializers, follow these rules. For more information, see [Collection expressions](../operators/collection-expressions.md). + +- Don't mix property initialization with element addition in the same initializer (**CS0747**). +- Include at least one element in collection initializers with braces (**CS1920**). +- Ensure the collection type implements `IEnumerable` (**CS1922**). +- Use collection initializers only with collection types (**CS1925**). +- Verify the `Add` method is accessible, takes one parameter matching the element type, and doesn't use `ref` or `out` modifiers (**CS1921**, **CS1954**). +- Resolve ambiguous `Add` method overloads (**CS1950**). +- Provide an explicit target type for collection expressions when the compiler can't infer it (**CS9176**, **CS9213**). +- Ensure the collection type is constructible with a parameterless constructor (**CS9174**, **CS9214**). +- Don't use `ref struct` types in collection expressions that may violate ref safety (**CS9203**). +- Update to a compatible runtime version for `ImmutableArray` collection expressions (**CS9210**). +- Implement enumeration patterns (like `GetEnumerator`) for spread operator support (**CS9212**). +- Avoid circular dependencies in collection initialization (**CS9222**). +- Don't use the spread operator in catch clause filter expressions (**CS9332**). ## Invalid array rank @@ -214,31 +202,37 @@ You access an element of an array by specifying the index for each axis declared - **CS0650**: *Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type.* - **CS1552**: *Array type specifier, `[]`, must appear before parameter name* -An array declaration consists of the following tokens, in order: +To declare arrays correctly, follow the proper syntax order. For more information, see [Arrays](../builtin-types/arrays.md) and the [C# Language Specification](~/_csharpstandard/standard/arrays.md#177-array-initializers) section on array initializers. + +An array declaration consists of these tokens in order: -1. The type of the array elements. For example, `int`, `string`, or `SomeClassType`. -1. The array brackets, optionally including commas to represent multi dimensions. -1. The variable name. +1. The type of array elements (for example, `int`, `string`, or `SomeClassType`) +2. The array brackets, optionally including commas for multiple dimensions +3. The variable name -When an array initialization specifies the array dimensions, you can specify the following properties: +When specifying array dimensions, you can use: - A number of elements in braces (`{` and `}`) - Empty brackets - One or more commas enclosed in brackets -For example, the following are valid array declarations: +The following examples show valid array declarations: :::code language="csharp" source="./snippets/array-warnings/Program.cs" id="ArrayDeclarations"::: -For more information, see the C# specification ([C# Language Specification](~/_csharpstandard/standard/arrays.md#177-array-initializers)) section on array initializers. - ## Invalid array length - **CS0248**: *Cannot create an array with a negative size* -- **CS0270**: *Array size cannot be specified in a variable declaration (try initializing with a 'new' expression* +- **CS0270**: *Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)* - **CS1586**: *Array creation must have array size or array initializer* -The length of each dimension of an array must be specified as part of the array initialization, not its declaration. The length of each dimension must be positive. You can specify the length either by using a `new` expression to allocate the array, or using an array initializer to assign all the elements. The following example shows both mechanisms: +To create arrays with valid lengths, specify the size during initialization, not declaration. For more information, see [Arrays](../builtin-types/arrays.md). + +- Specify array length as part of initialization, not declaration (**CS0270**). +- Use only positive integers for array dimensions (**CS0248**). +- Provide either a size in a `new` expression or an array initializer (**CS1586**). + +The following example shows both mechanisms: :::code language="csharp" source="./snippets/array-warnings/Program.cs" id="ArrayInitializers"::: @@ -247,41 +241,97 @@ The length of each dimension of an array must be specified as part of the array - **CS0611**: *Array elements cannot be of type 'type'* - **CS0719**: *Array elements cannot be of static type* - **CS0820**: *Cannot assign array initializer to an implicitly typed local* -- **CS0826**: *No best type found for implicitly typed array.* +- **CS0826**: *No best type found for implicitly typed array* + +To use arrays with correct element types, follow these type restrictions. For more information, see [Implicitly typed local variables](../statements/declarations.md#implicitly-typed-local-variables) and [best common type](~/_csharpstandard/standard/expressions.md#126316-finding-the-best-common-type-of-a-set-of-expressions). -There are some types that cannot be used as the type of an array. These types include and . The type of an array can't be a `static` class, because instances of a `static` class can't be created. +- Don't use restricted types like and as array element types (**CS0611**). +- Don't use `static` classes as array element types because instances can't be created (**CS0719**). +- Initialize implicitly typed arrays with a `new` expression (**CS0820**). +- Ensure all elements in an implicitly typed array initializer have a best common type (**CS0826**). -You can declare arrays as [implicitly typed local variables](../statements/declarations.md#implicitly-typed-local-variables). The array must be initialized using a `new` expression. In addition, all elements in an array initializer must have a [best common type](~/_csharpstandard/standard/expressions.md#126316-finding-the-best-common-type-of-a-set-of-expressions). The following examples show how to declare an implicitly typed array: +The following examples show how to declare implicitly typed arrays: :::code language="csharp" source="./snippets/array-warnings/Program.cs" id="ImplicitInitializer"::: -You can ensure the best common type using any of the following techniques: +To ensure a best common type, use any of these techniques: - Give the array an explicit type. - Give all array elements the same type. -- Provide explicit casts on those elements that might be causing the problem. +- Provide explicit casts on elements that might be causing the problem. -## Invalid collection builder +## Invalid array initializer -The following errors indicate errors in your collection builder type: +- **CS0623**: *Array initializers can only be used in a variable or field initializer. Try using a new expression instead.* +- **CS0846**: *A nested array initializer is expected* +- **CS1925**: *Cannot initialize object of type 'type' with a collection initializer.* -- **CS9185**: *The `CollectionBuilderAttribute` builder type must be a non-generic class or struct.* -- **CS9186**: *The `CollectionBuilderAttribute` method name is invalid.* -- **CS9187**: *Could not find an accessible method with the expected signature: a static method with a single parameter of type `ReadOnlySpan`; and correct return type.* -- **CS9188**: *Type has a `CollectionBuilderAttribute` but no element type.* +These errors indicate invalid array initializer syntax. For more information, see [Arrays](../builtin-types/arrays.md). + +To create valid array initializers: -These errors indicate that your collection builder type needs modification. Remember the following rules: +- Use array initializers only in variable or field declarations (**CS0623**). Use a `new` expression in other contexts. +- Balance braces (`{` and `}`) around elements or child arrays (**CS0846**). +- Ensure the initializing expression matches the number of arrays in a jagged array initialization. +- Use collection initializers only with collection types, not with arrays or other types (**CS1925**). -- The collection type must have an iteration type. In other words, you can [`foreach`](~/_csharpstandard/standard/statements.md#1395-the-foreach-statement) the type as a collection. -- The collection builder type can't be a generic type. -- The method name specified on the must be a valid method name. For example, it can't be finalizer, or other name that contains invalid identifier characters. -- The collection builder method must be an accessible static method. It must return the collection type, and it must take a parameter of `ReadOnlySpan` where `T` matches the element type of the collection. +## Invalid collection builder + +- **CS9175**: *An expression tree may not contain a collection expression.* +- **CS9177**: *The 'CollectionBuilderAttribute' builder method return type must match collection type used in 'betterness'.* +- **CS9178**: *There is no target type for the natural type 'type'.* +- **CS9179**: *Collection expression type must have an applicable constructor that can be called with no arguments.* +- **CS9180**: *The 'CollectionBuilderAttribute' builder method must be a static method.* +- **CS9181**: *The 'CollectionBuilderAttribute' builder method parameter type must match parameter 'ReadOnlySpan<{0}>'* +- **CS9182**: *Invalid 'CollectionBuilderAttribute'. No matching '{0}' method found on builder type '{1}'.* +- **CS9183**: *The 'CollectionBuilderAttribute' method return type must be a non-abstract, non-interface type usable as a 'type'* +- **CS9185**: *A *static type* cannot be used as a type argument.* +- **CS9186**: *The `CollectionBuilderAttribute` method name is invalid.* +- **CS9187**: *Could not find an accessible 'Create' method with the expected signature: a static method with a single parameter of type 'ReadOnlySpan<{0}>' and return type '{1}'.* +- **CS9188**: *'scoped' cannot be used as a modifier on a collection expression type parameter.* +- **CS9190**: *The 'CollectionBuilderAttribute' method 'builderMethod' is inapplicable because it's generic.* +- **CS9192**: *Inline array conversions cannot be used with collection expressions.* +- **CS9193**: *Argument 'argument' may not be passed with the 'ref' keyword.* +- **CS9194**: *Argument 'argument' may not be passed with the 'out' keyword* +- **CS9195**: *Argument 'argument' may not be passed with the 'in' keyword* +- **CS9196**: *Feature 'collection expression' is not available in C# 'version'. Please use language version 'requiredVersion' or greater.* +- **CS9197**: *Feature 'inline arrays' is not available in C# 'version'. Please use language version 'requiredVersion' or greater.* +- **CS9198**: *Feature 'ref and unsafe in async and iterator methods' is not available in C# 'version'. Please use language version 'requiredVersion' or greater.* +- **CS9199**: *Feature 'collection expression' is not available in C# 'version'. Please use language version 'requiredVersion' or greater.* +- **CS9202**: *Feature 'ref readonly parameters' is not available in C# 'version'. Please use language version 'requiredVersion' or greater.* +- **CS9208**: *'nameof' operator cannot be used on an inline array access.* +- **CS9209**: *A ref-returning property 'property' cannot be used as a value argument.* +- **CS9211**: *The expression must be of type 'type' because it's being assigned by reference* +- **CS9212**: *Cannot use collection expression as the value in a fixed statement* +- **CS9217**: *A 'ref' local cannot be preserved across 'await' or 'yield' boundary.* +- **CS9218**: *'paramName' is a ref struct and cannot be the type of a parameter* +- **CS9221**: *The type 'type' may not be a ref struct or a type parameter allowing ref structs in order to use it as parameter 'parameter' in the generic type or method 'member'* +- **CS9223**: *A struct that contains 'ref' fields cannot be used in a collection expression.* +- **CS9228**: *Non-variable declaration of a ref struct is not allowed* +- **CS9232**: *Partial method declarations have signature differences.* +- **CS9233**: *The 'file' modifier can be used only on types defined in top level in a compilation unit* + +To create collection expressions with collection builder attributes correctly, follow these requirements. For more information, see [Collection expressions](../operators/collection-expressions.md). + +- Ensure the target type has an iteration type that supports `foreach` (**CS9188**). +- Don't use generic types as collection builder types (**CS9185**). +- Verify the method name specified in `CollectionBuilderAttribute` is valid (**CS9186**). +- Apply `CollectionBuilderAttribute` only with static methods that match the required signature: return the collection type and take a `ReadOnlySpan` parameter where `T` matches the element type (**CS9180**, **CS9181**, **CS9182**, **CS9183**, **CS9187**, **CS9190**). +- Ensure the return type matches and isn't abstract or an interface (**CS9177**, **CS9183**). +- Don't use ref structs or types with ref fields in collection expressions (**CS9218**, **CS9221**, **CS9223**, **CS9228**). +- Avoid using collection expressions in expression trees (**CS9175**). +- Use the correct language version for collection expressions and related features (**CS9196**, **CS9197**, **CS9198**, **CS9199**, **CS9202**). ## Common language specification warnings - **CS3007**: *Overloaded method 'method' differing only by unnamed array types is not CLS-compliant* - **CS3016**: *Arrays as attribute arguments is not CLS-compliant* +To write CLS-compliant code with arrays, follow these guidelines. For more information, see [Language independence](../../../standard/language-independence.md). + +- Don't create overloaded methods that differ only in array element types (**CS3007**). +- Don't use arrays as attribute arguments (**CS3016**). + CS3007 occurs if you have an overloaded method that takes a jagged array and the only difference between the method signatures is the element type of the array. To avoid this error, consider using a rectangular array rather than a jagged array or, if CLS Compliance isn't needed, remove the attribute. For more information on CLS Compliance, see [Language independence and language-independent components](../../../standard/language-independence.md). CS3016 indicates that not compliant with the Common Language Specification (CLS) to pass an array to an attribute. For more information on CLS compliance, see [Language independence and language-independent components](../../../standard/language-independence.md). From 6ffa62c8854ce1b33537c6f6ab58ac001364af8e Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Fri, 7 Nov 2025 13:59:47 -0500 Subject: [PATCH 4/6] edit pass on extension declarations Add final errors introduced in C# 14 for extensions. Perform an edit pass to match the improved format. --- .../extension-declarations.md | 104 ++++++++++-------- 1 file changed, 58 insertions(+), 46 deletions(-) diff --git a/docs/csharp/language-reference/compiler-messages/extension-declarations.md b/docs/csharp/language-reference/compiler-messages/extension-declarations.md index 3a27bb5cd09d3..3afc8068b58f5 100644 --- a/docs/csharp/language-reference/compiler-messages/extension-declarations.md +++ b/docs/csharp/language-reference/compiler-messages/extension-declarations.md @@ -1,7 +1,8 @@ --- -title: "Errors and warnings related to extension declarations" +title: "Resolve errors and warnings related to extension declarations" description: "These errors and warnings indicate that you need to modify the declaration of an extension method using the `this` modifier on the first parameter, or an extension declaration" -ms.date: 10/16/2025 +ms.date: 11/07/2025 +ai-usage: ai-assisted f1_keywords: - "CS1100" - "CS1101" @@ -91,8 +92,13 @@ helpviewer_keywords: - "CS9329" - "CS9339" --- -# Errors and warnings related to extension methods declared with `this` parameters or `extension` blocks +# Resolve errors and warnings in extension member declarations +This article covers the following compiler errors: + + - [**CS1100**](#errors-related-to-this-parameter-extension-methods): *Method has a parameter modifier '`this`' which is not on the first parameter* - [**CS1101**](#errors-related-to-this-parameter-extension-methods): *The parameter modifier '`ref`' cannot be used with '`this`'.* - [**CS1102**](#common-errors-on-extension-declarations): *The parameter modifier '`out`' cannot be used with '`this`'.* @@ -140,11 +146,9 @@ helpviewer_keywords: ## Common errors on extension declarations -The compiler emits these errors when you violate rules that apply to all extension member declarations, regardless of the syntax chosen: - - **CS1102**: *The parameter modifier '`out`' cannot be used with '`this`'.* -- **CS1106**: *Extension methods must be defined in a non generic static class.* - **CS1103**: *The first parameter of an extension method cannot be of a pointer type.* +- **CS1106**: *Extension methods must be defined in a non generic static class.* - **CS1109**: *Extension Methods must be defined on top level static classes, 'name' is a nested class.* - **CS1113**: *Extension method defined on a value type cannot be used to create delegates.* - **CS1743**: *Cannot specify a default value for the 'this' parameter.* @@ -152,18 +156,19 @@ The compiler emits these errors when you violate rules that apply to all extensi - **CS9284**: *The receiver parameter of an extension cannot have a default value.* - **CS9285**: *An extension container can have only one receiver parameter.* -Any extension declaration must follow these rules: +The compiler emits these errors when you violate rules that apply to all extension member declarations, regardless of the syntax chosen. For more information, see [Extension methods](../../programming-guide/classes-and-structs/extension-methods.md). -- Its containing type (`class` or `struct`) must be non-generic and `static`. -- Its containing type must be a top-level type. It can't be nested in another type. -- Members that extend an instance of a value type can't be converted to delegates. -- The receiver parameter can't include the `out` parameter modifier. -- The receiver parameter can't have a default argument value. -- Pointer types can't be extended. In other words, the parameter you apply the `this` modifier to can't be a pointer type. +To declare extension members correctly, follow these requirements: -## Errors related to extension block declarations +- Declare the containing type as a non-generic `static` class or struct (**CS1106**, **CS9283**). +- Declare the containing type at the top level, not nested within another type (**CS1109**, **CS9283**). +- Don't convert extension methods on value types to delegates (**CS1113**). Create a regular method instead. +- Don't use the `out` parameter modifier on the receiver parameter (**CS1102**). +- Don't provide default values for the receiver parameter (**CS1743**, **CS9284**). +- Don't extend pointer types (**CS1103**). The parameter you apply the `this` modifier to can't be a pointer type. +- Declare only one receiver parameter per extension container (**CS9285**). -These errors are specific to extension blocks, a C# 14 feature. Extension blocks are declared using the `extension` keyword in a static class. The `extension` declares the type and name of the receiver. All members inside the block declared with `extension` are extension members for that receiver: +## Errors related to extension block declarations - **CS9281**: *Extension declarations may not have a name.* - **CS9282**: *Extension declarations can include only methods or properties.* @@ -194,52 +199,59 @@ These errors are specific to extension blocks, a C# 14 feature. Extension blocks - **CS9323**: *Cannot declare instance extension operator for a type that is not known to be a struct and is not known to be a class.* - **CS9326**: *'`name`': extension member names cannot be the same as their extended type.* - **CS9329**: *This extension block collides with another extension block. They result in conflicting content-based type names in metadata.* +- **CS9339**: *The extension resolution is ambiguous between the following members.* -The contextual keyword [`extension`](../keywords/extension.md) declares an extension block. It can't be used for a type. - -Extension declarations must follow these rules: - -- The extension can't include a name token. The extension declares the receiver only. -- The receiver parameter can't have a default value. +These errors are specific to extension blocks, a C# 14 feature. Extension blocks are declared using the [`extension`](../keywords/extension.md) contextual keyword in a static class. For more information, see [Extension methods](../../programming-guide/classes-and-structs/extension-methods.md). -Extension members declared in an extension block must follow these rules, in addition to the [common rules](#common-errors-on-extension-declarations): +To declare extension blocks correctly, follow these requirements: -- Only methods and properties are valid extension member types. Extension members can extend an instance, or a type. -- The extension must provide a parameter name for the receiver in order to contain members that extend an instance. -- The receiver parameter name must be unique in that extension block. -- All extension members must use all type parameters declared on the extension. They can add more type parameters. -- Extension blocks can't be nested within another extension block. +- Don't include a name token in the extension declaration (**CS9281**). The extension declares the receiver only. +- Don't provide default values for the receiver parameter (**CS9284**, covered in [common errors](#common-errors-on-extension-declarations)). +- Don't use the `extension` keyword for types or aliases (**CS9306**). It's a contextual keyword for extension blocks only. -**CS9316** is emitted when you attempt to use an extension member as an argument to the `nameof` operator. Extension members aren't allowed in this context. +To declare extension members in extension blocks correctly, follow these requirements in addition to the [common rules](#common-errors-on-extension-declarations): -**CS9317**, **CS9318**, **CS9319**, **CS9320**, **CS9321**, **CS9322**, and **CS9323** are operator-related errors in extension blocks: +- Include only methods or properties as extension members (**CS9282**). Other member types aren't supported. +- Provide a parameter name for the receiver to contain instance extension members (**CS9303**). +- Ensure the receiver parameter name is unique within the extension block and doesn't conflict with type parameters (**CS9287**, **CS9288**, **CS9289**, **CS9290**, **CS9291**, **CS9292**, **CS9294**). +- Reference all type parameters declared on the extension in the extended type (**CS9295**). Additional type parameters can be added on individual members. +- Don't nest extension blocks within other extension blocks (**CS9309**). +- Use the `ref` modifier on the receiver parameter only with value types or generic types constrained to struct (**CS9300**). +- Use the `in` or `ref readonly` modifier on the receiver parameter only with concrete (non-generic) value types (**CS9301**). +- Don't use modifiers on unnamed receiver parameters (**CS9305**). +- Don't declare `protected` members in extension blocks (**CS9302**). Extension members must be accessible where the extension is in scope. +- Don't declare `init`-only accessors in extension blocks (**CS9304**). Use regular property setters instead. +- Don't use extension members as arguments to the `nameof` operator (**CS9316**). +- Choose member names that differ from the extended type name (**CS9326**). +- Ensure extension blocks have unique content-based type names in metadata (**CS9329**). Consolidate or differentiate extension blocks to avoid conflicts. +- Resolve ambiguous extension member calls by providing more specific type information or using qualified names (**CS9339**). -- **CS9317**: Unary operators must have the extended type as their parameter. -- **CS9318**: Increment (`++`) and decrement (`--`) operators must have the extended type as their parameter. -- **CS9319**: Binary operators must have at least one parameter that is the extended type. -- **CS9320**: Shift operators must have the extended type as their first operand. -- **CS9321**: You can't declare user-defined operators in extension blocks that extend static classes. -- **CS9322**: When extending a struct with instance operators, the receiver parameter must use the `ref` modifier. -- **CS9323**: You can't declare instance operators for types that aren't constrained to be either a struct or a class. +### Extension block operator requirements -**CS9326** is emitted when an extension member has the same name as the extended type. Choose a different name for the member. +Extension blocks support user-defined operators with specific requirements: -**CS9329** occurs when two extension blocks result in conflicting content-based type names in the compiled metadata. This typically happens when multiple extension blocks with the same receiver type and similar characteristics are declared. Consolidate the extension blocks or differentiate them in a way that produces unique metadata names. +- Unary operators must have the extended type as their parameter (**CS9317**). +- Increment (`++`) and decrement (`--`) operators must have the extended type as their parameter (**CS9318**). +- Binary operators must have at least one parameter that is the extended type (**CS9319**). +- Shift operators must have the extended type as their first operand (**CS9320**). +- Don't declare user-defined operators in extension blocks that extend static classes (**CS9321**). +- When extending a struct with instance operators, use the `ref` modifier on the receiver parameter (**CS9322**). +- Don't declare instance operators for types that aren't constrained to be either a struct or a class (**CS9323**). ## Errors related to `this` parameter extension methods -These errors are specific to extension methods where you declare the receiver by adding the `this` modifier to the first parameter of the method: - - **CS1100**: *Method has a parameter modifier '`this`' which is not on the first parameter* - **CS1101**: *The parameter modifier '`ref`' cannot be used with '`this`'.* - **CS1105**: *Extension methods must be static.* - **CS1110**: *Cannot define a new extension because the compiler required type cannot be found. Are you missing a reference to System.Core.dll?* - **CS1112**: *Do not use ''. Use the '`this`' keyword instead.* -An extension method where the receiver instance includes the `this` modifier must follow these rules, in addition to the [common rules](#common-errors-on-extension-declarations): +These errors are specific to extension methods where you declare the receiver by adding the `this` modifier to the first parameter. For more information, see [Extension methods](../../programming-guide/classes-and-structs/extension-methods.md). + +To declare `this` parameter extension methods correctly, follow these requirements in addition to the [common rules](#common-errors-on-extension-declarations): -- The method must have the `static` modifier. -- The `this` parameter modifier must be applied to the first parameter. It can't be applied to any other parameters on the method. -- The `ref` `out` parameter modifier can't be applied to the first parameter. To apply `ref`, you need to convert to an extension block. -- In .NET Framework apps, `System.Core.dll` must be added as a reference. -- You must specify the `this` modifier on the first parameter. You can't directly use the attribute instead. +- Add the `static` modifier to the method (**CS1105**). +- Apply the `this` parameter modifier only to the first parameter (**CS1100**). +- Don't combine the `ref` modifier with the `this` modifier (**CS1101**). To use `ref`, convert to an extension block. +- Add a reference to `System.Core.dll` in .NET Framework apps (**CS1110**). +- Use the `this` modifier on the first parameter instead of directly applying the attribute (**CS1112**). From 7831db960bff44e7487e7074276634cce255ebb4 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Fri, 7 Nov 2025 14:12:13 -0500 Subject: [PATCH 5/6] Edit pass and update dates After adding the final diagnostics for C# 14, update this file to match the more recent style. --- .../overloaded-operator-errors.md | 102 ++++++++++++------ .../pattern-matching-warnings.md | 73 +++++++++---- 2 files changed, 126 insertions(+), 49 deletions(-) diff --git a/docs/csharp/language-reference/compiler-messages/overloaded-operator-errors.md b/docs/csharp/language-reference/compiler-messages/overloaded-operator-errors.md index e124b86baac49..555ec6ab4b978 100644 --- a/docs/csharp/language-reference/compiler-messages/overloaded-operator-errors.md +++ b/docs/csharp/language-reference/compiler-messages/overloaded-operator-errors.md @@ -1,6 +1,6 @@ --- -title: Errors and warnings related to user defined operator declarations -description: This article helps you diagnose and correct compiler errors and warnings when you declare user defined operators in your types +title: Resolve errors and warnings related to user-defined operator declarations +description: This article helps you diagnose and correct compiler errors and warnings when you declare user-defined operators in your types f1_keywords: - "CS0056" - "CS0057" @@ -79,12 +79,12 @@ helpviewer_keywords: - "CS9340" - "CS9341" - "CS9342" -ms.date: 10/15/2025 +ms.date: 11/07/2025 ai-usage: ai-assisted --- -# Errors and warnings for overloaded, or user-defined operator declarations +# Resolve errors and warnings in user-defined operator declarations -There are several errors related to declaring overloaded operators. Overloaded operators are also referred to as user-defined operators +This article covers the following compiler errors: +- [**CS8509**](#incomplete-pattern-matching): *The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '...' is not covered.* +- [**CS9134**](#switch-expression-syntax-errors): *A switch expression arm does not begin with a 'case' keyword.* +- [**CS9135**](#switch-expression-syntax-errors): *A constant value of type is expected* +- [**CS9335, CS9336**](#redundant-patterns): *The pattern is redundant.* +- [**CS9337**](#redundant-patterns): *The pattern is too complex to analyze for redundancy.* + +## Switch expression syntax errors - **CS9134**: *A switch expression arm does not begin with a 'case' keyword.* - **CS9135**: *A constant value of type is expected* -- **CS9335, CS9336**: *The pattern is redundant.* -- **CS9337**: *The pattern is too complex to analyze for redundancy.* -The compiler generates the following warnings for incomplete pattern matching expressions: +To write switch expressions correctly, follow the proper syntax rules. For more information, see [Switch expression](../operators/switch-expression.md). -- **CS8509**: *The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '...' is not covered.* +- Don't use the `case` keyword in switch expressions (**CS9134**). The `case` keyword is used in switch statements, not switch expressions. In a switch expression, each arm consists of a pattern, an optional case guard, the `=>` token, and an expression. +- Use constant values in patterns, not variables (**CS9135**). Pattern matching requires compile-time constants for value patterns. -The compiler generates CS9134 to help you convert a switch statement to a switch expression. The `case` keyword isn't used in a switch expression. If you have the `case` keyword in a switch expression, it must be removed: +The following example demonstrates the syntax error with `case`: ```csharp var answer = x switch @@ -40,24 +55,46 @@ var answer = x switch } ``` -The compiler generates CS9135 when the pattern isn't a constant value. You can't create pattern matching expressions to match against a variable. +To fix this error, remove the `case` keyword: + +```csharp +var answer = x switch +{ + 0 => false, + 1 => true, +} +``` + +## Incomplete pattern matching + +- **CS8509**: *The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '...' is not covered.* + +To create exhaustive switch expressions, cover all possible input values. For more information, see [Switch expression](../operators/switch-expression.md) and [Switch statement](../statements/selection-statements.md#the-switch-statement). + +Add switch arms that handle all possible input values. Use the discard pattern (`_`) to match any remaining values that you don't need to handle explicitly. -The following code snippets generate CS8509: +The following example generates CS8509: :::code language="csharp" source="./snippets/pattern-matching-warnings/Switch.cs" id="SwitchNotAllPossibleValues"::: -To address this warning, add switch arms that cover all possible input values. For example: +To fix this warning, add a default arm: :::code language="csharp" source="./snippets/pattern-matching-warnings/Switch.cs" id="SwitchAllPossibleValues"::: -The `_` pattern matches all remaining values. One scenario for the `_` pattern is matching invalid values, as shown in the preceding example. +The `_` pattern matches all remaining values. You can use this pattern to handle invalid or unexpected values. -The compiler generates CS9335 when you wrote a pattern where an `or` is redundant: +## Redundant patterns -:::code language="csharp" source="./snippets/pattern-matching-warnings/Switch.cs" id="RedundantPattern"::: +- **CS9335, CS9336**: *The pattern is redundant.* +- **CS9337**: *The pattern is too complex to analyze for redundancy.* -This warning indicates you likely meant `is not (null or 42)` or `is not (int or string)` instead. +To write clear pattern matching expressions, avoid redundant patterns. For more information, see [Patterns](../operators/patterns.md). -You can construct patterns that are too complex to analyze for redundancy. If you do that, the compiler warns you with CS9337. +- Review patterns that the compiler identifies as redundant (**CS9335**, **CS9336**). Redundant patterns can indicate a logic error where you meant to use `not` or different logical operators. +- Simplify complex patterns that are too difficult for the compiler to analyze (**CS9337**). Break down complex patterns into simpler, more maintainable expressions. + +The following example demonstrates a redundant pattern: + +:::code language="csharp" source="./snippets/pattern-matching-warnings/Switch.cs" id="RedundantPattern"::: -For more information, see [Switch](../statements/selection-statements.md#the-switch-statement). +This warning indicates you likely meant `is not (null or 42)` or `is not (int or string)` instead of using `or` at the top level. From d596a14648f6de561aa1c6596e20969404442cf4 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Fri, 7 Nov 2025 14:58:13 -0500 Subject: [PATCH 6/6] Apply suggestions from code review Co-authored-by: Genevieve Warren <24882762+gewarren@users.noreply.github.com> --- .../compiler-messages/array-declaration-errors.md | 8 ++++---- .../compiler-messages/pattern-matching-warnings.md | 4 ---- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/docs/csharp/language-reference/compiler-messages/array-declaration-errors.md b/docs/csharp/language-reference/compiler-messages/array-declaration-errors.md index b4ee7126f28b7..51fc3bac11d09 100644 --- a/docs/csharp/language-reference/compiler-messages/array-declaration-errors.md +++ b/docs/csharp/language-reference/compiler-messages/array-declaration-errors.md @@ -148,7 +148,7 @@ In addition, the following warnings are covered in this article: To access array elements correctly, follow these indexing rules. For more information, see [Arrays](../builtin-types/arrays.md). -- Specify the same number of indices as declared dimensions (**CS0022**). A one-dimensional array needs one index, a three-dimensional array needs three indices. +- Specify the same number of indices as declared dimensions (**CS0022**). A one-dimensional array needs one index; a three-dimensional array needs three indices. - Use only non-negative integers for array indices (**CS0251**). Array indices always start at zero. ## Invalid collection initializer @@ -206,9 +206,9 @@ To declare arrays correctly, follow the proper syntax order. For more informatio An array declaration consists of these tokens in order: -1. The type of array elements (for example, `int`, `string`, or `SomeClassType`) -2. The array brackets, optionally including commas for multiple dimensions -3. The variable name +1. The type of array elements (for example, `int`, `string`, or `SomeClassType`). +2. The array brackets, optionally including commas for multiple dimensions. +3. The variable name. When specifying array dimensions, you can use: diff --git a/docs/csharp/language-reference/compiler-messages/pattern-matching-warnings.md b/docs/csharp/language-reference/compiler-messages/pattern-matching-warnings.md index 5e18f76c49f0a..31a77b4f18142 100644 --- a/docs/csharp/language-reference/compiler-messages/pattern-matching-warnings.md +++ b/docs/csharp/language-reference/compiler-messages/pattern-matching-warnings.md @@ -21,10 +21,6 @@ ai-usage: ai-assisted This article covers the following compiler errors and warnings: -# Resolve errors and warnings in pattern matching expressions - -This article covers the following compiler errors and warnings: -