From c5b2ce74ab5aa926d313c42c23cb725b665dcf68 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Thu, 20 Aug 2026 10:28:28 -0400 Subject: [PATCH 1/6] docs: consolidate expression-form context restriction diagnostics (CS8115, CS8185, CS8209, CS8310, CS8312) This article consolidates five compiler diagnostics related to invalid expression contexts: - CS8115: Throw expressions in restricted contexts - CS8185: Declaration expressions in restricted contexts - CS8209: Void-returning expression restrictions - CS8310: Operator binding for null/default/new - CS8312: Default literal target type requirements Content organized by remediation strategy. Codes removed from catch-all. CS8188 preserved in expression-tree-restrictions.md per issue guidance. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../expression-form-restrictions.md | 82 +++++++++++++++++++ docs/csharp/language-reference/toc.yml | 5 ++ ...n-t-have-specifics-on-this-csharp-error.md | 5 -- 3 files changed, 87 insertions(+), 5 deletions(-) create mode 100644 docs/csharp/language-reference/compiler-messages/expression-form-restrictions.md diff --git a/docs/csharp/language-reference/compiler-messages/expression-form-restrictions.md b/docs/csharp/language-reference/compiler-messages/expression-form-restrictions.md new file mode 100644 index 0000000000000..a25d7d4479217 --- /dev/null +++ b/docs/csharp/language-reference/compiler-messages/expression-form-restrictions.md @@ -0,0 +1,82 @@ +--- +title: "Resolve errors from invalid expression contexts" +description: "This article helps you diagnose and correct compiler errors and warnings from expressions that appear in contexts where they are not permitted" +f1_keywords: + - "CS8115" + - "CS8185" + - "CS8209" + - "CS8310" + - "CS8312" +helpviewer_keywords: + - "CS8115" + - "CS8185" + - "CS8209" + - "CS8310" + - "CS8312" +ms.date: 08/20/2026 +ai-usage: ai-assisted +--- + +# Resolve errors from invalid expression contexts + +This article covers the following compiler errors and warnings: + + + +- [**CS8115**](#throw-expressions-in-expression-contexts): *A throw expression is not allowed in this context.* +- [**CS8185**](#declaration-expressions-in-restricted-contexts): *A declaration is not allowed in this context.* +- [**CS8209**](#void-returning-expression-restrictions): *A value of type 'void' may not be assigned.* +- [**CS8310**](#type-binding-for-default-literals-and-typeless-expressions): *Operator 'operator' cannot be applied to operand 'operand'* +- [**CS8312**](#type-binding-for-default-literals-and-typeless-expressions): *Use of default literal is not valid in this context* + +## Throw expressions in expression contexts + +- **CS8115**: *A throw expression is not allowed in this context.* + +The compiler permits throw expressions only in specific contexts where an expression can appear and the exception is immediately propagated. Move the `throw` expression to a valid context, such as: + +- A conditional arm of a ternary or switch expression (where the throw is one of the arms). +- An assignment to evaluate the throw in place of the assigned value. +- An argument to a method call where throwing is appropriate. +- A statement in a lambda or local function body (not within a method that must return a value). + +If the throw expression appears in a position where the expression value must be used (such as within arithmetic or operator expressions), extract it into a separate statement or conditional check. + +## Declaration expressions in restricted contexts + +- **CS8185**: *A declaration is not allowed in this context.* + +The compiler permits declaration expressions (`out var`, pattern-matching declarations) only in specific positions. These include `out` parameter declarations in method calls and in certain statement contexts. Remove the declaration expression from contexts where it's not permitted, such as: + +- Lambda expression bodies (unless the lambda is a statement body). +- Query expressions where the grammar forbids declarations. +- Inside attribute arguments. +- In contexts that require a read-only expression. + +If you need to use an out variable, call the method in a separate statement, then reference the resulting variable. Alternatively, use a local variable declaration before the expression. + +## Type binding for default literals and typeless expressions + +- **CS8310**: *Operator 'operator' cannot be applied to operand 'operand'* +- **CS8312**: *Use of default literal is not valid in this context* + +The `default` literal and typeless expressions (such as `null` or `new` without a target type) require a target type for the compiler to infer the expression type. When an operator is applied to these expressions without enough context, the compiler cannot determine the operand type. + +Provide the target type by: + +- Adding an explicit type cast: `(int)default` or `(MyType)new`. +- Assigning to a typed variable: `int x = default;`. +- Using a method parameter or return type to establish context. +- Using the verbose form `default(Type)` instead of the `default` literal for clarity. + +If the operator itself requires a specific type, ensure the operand can be implicitly converted to that type. + +## Void-returning expression restrictions + +- **CS8209**: *A value of type 'void' may not be assigned.* + +The `void` type is not a value type; it represents the absence of a return value. Remove the assignment of void-returning expressions. If you need to invoke a method that returns `void`, call it as a standalone statement. If you need a result, use a method that returns a value instead. + +Ensure that expressions assigned to variables always have a meaningful return type. diff --git a/docs/csharp/language-reference/toc.yml b/docs/csharp/language-reference/toc.yml index 81dedbab5cf4c..80c935ad20af8 100644 --- a/docs/csharp/language-reference/toc.yml +++ b/docs/csharp/language-reference/toc.yml @@ -732,6 +732,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: Expression-form restrictions + href: ./compiler-messages/expression-form-restrictions.md + displayName: > + throw expressions, declaration expressions, invalid contexts, + CS8115, CS8185, CS8209, CS8310, CS8312 - name: Local functions href: ./compiler-messages/local-function-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 10affda335669..0d31e10203c57 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 @@ -157,9 +157,7 @@ f1_keywords: - "CS8111" - "CS8113" # C# 7.0 diagnostics - - "CS8115" - "CS8180" - - "CS8185" - "CS8188" - "CS8189" - "CS8190" @@ -168,15 +166,12 @@ f1_keywords: - "CS8202" - "CS8205" - "CS8206" - - "CS8209" # C# 7.1 diagnostics - "CS8300" - "CS8301" - "CS8305" - "CS8308" - "CS8309" - - "CS8310" - - "CS8312" # C# 7.2 diagnostics - "CS8323" - "CS8328" From ffe83efb7e4df7897c08cc35234ff65ff0eb7566 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Thu, 20 Aug 2026 11:54:32 -0400 Subject: [PATCH 2/6] docs: expand expression-form diagnostics to eight codes with keyword context restrictions (CS0175, CS0186, CS1547) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Consolidate three standalone diagnostic articles (CS0175, CS0186, CS1547) into expression-form-restrictions.md, broadening the article scope from 5 to 8 codes while maintaining thematic coherence: MERGED CODES: - CS0175: Use of keyword 'base' is not valid in this context - CS0186: Use of null is not valid in this context - CS1547: Keyword 'void' cannot be used in this context CHANGES: - Updated expression-form-restrictions.md with new 'Keyword and literal context restrictions' section containing substantive guidance from the three deleted standalone articles - Merged all unique remediation information and examples - Updated front matter f1_keywords and helpviewer_keywords (8 codes) - Updated master error list with all 8 codes and exact Roslyn messages - Updated TOC displayName with all 8 codes - Removed old TOC entries for CS0175, CS0186, CS1547 - Created three redirects from old paths to new destination anchors - Deleted three now-retired standalone files FOOTPRINT REDUCTION: 3 standalone files → 1 consolidated article VERIFICATION: - YAML front matter valid - All 8 codes present in f1_keywords/helpviewer_keywords - No trailing whitespace - Redirect JSON valid (1415 total entries) - Exact Roslyn messages preserved per Bill's requirements Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .openpublishing.redirection.csharp.json | 15 ++++ .../expression-form-restrictions.md | 78 +++++++++++++++++++ docs/csharp/language-reference/toc.yml | 9 +-- docs/csharp/misc/cs0175.md | 46 ----------- docs/csharp/misc/cs0186.md | 31 -------- docs/csharp/misc/cs1547.md | 32 -------- 6 files changed, 96 insertions(+), 115 deletions(-) delete mode 100644 docs/csharp/misc/cs0175.md delete mode 100644 docs/csharp/misc/cs0186.md delete mode 100644 docs/csharp/misc/cs1547.md diff --git a/.openpublishing.redirection.csharp.json b/.openpublishing.redirection.csharp.json index 213055a1d48e7..3ee9e1a656812 100644 --- a/.openpublishing.redirection.csharp.json +++ b/.openpublishing.redirection.csharp.json @@ -5840,6 +5840,21 @@ { "source_path_from_root": "/docs/csharp/programming-guide/statements-expressions-operators/how-to-define-value-equality-for-a-type.md", "redirect_url": "/dotnet/csharp/fundamentals/expressions/equality#implement-equality-yourself-when-a-type-cant-be-a-record" + }, + { + "source_path": "docs/csharp/misc/cs0175.md", + "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/expression-form-restrictions#base-keyword-in-invalid-contexts", + "redirect_document_id": "false" + }, + { + "source_path": "docs/csharp/misc/cs0186.md", + "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/expression-form-restrictions#null-in-iteration-contexts", + "redirect_document_id": "false" + }, + { + "source_path": "docs/csharp/misc/cs1547.md", + "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/expression-form-restrictions#void-keyword-in-invalid-type-contexts", + "redirect_document_id": "false" } ] } diff --git a/docs/csharp/language-reference/compiler-messages/expression-form-restrictions.md b/docs/csharp/language-reference/compiler-messages/expression-form-restrictions.md index a25d7d4479217..9fa6ffa9f0628 100644 --- a/docs/csharp/language-reference/compiler-messages/expression-form-restrictions.md +++ b/docs/csharp/language-reference/compiler-messages/expression-form-restrictions.md @@ -2,12 +2,18 @@ title: "Resolve errors from invalid expression contexts" description: "This article helps you diagnose and correct compiler errors and warnings from expressions that appear in contexts where they are not permitted" f1_keywords: + - "CS0175" + - "CS0186" + - "CS1547" - "CS8115" - "CS8185" - "CS8209" - "CS8310" - "CS8312" helpviewer_keywords: + - "CS0175" + - "CS0186" + - "CS1547" - "CS8115" - "CS8185" - "CS8209" @@ -25,12 +31,84 @@ This article covers the following compiler errors and warnings: That's by design. The text closely matches the text of the compiler error / warning for SEO purposes. --> +- [**CS0175**](#keyword-and-literal-context-restrictions): *Use of keyword 'base' is not valid in this context* +- [**CS0186**](#keyword-and-literal-context-restrictions): *Use of null is not valid in this context* +- [**CS1547**](#keyword-and-literal-context-restrictions): *Keyword 'void' cannot be used in this context* - [**CS8115**](#throw-expressions-in-expression-contexts): *A throw expression is not allowed in this context.* - [**CS8185**](#declaration-expressions-in-restricted-contexts): *A declaration is not allowed in this context.* - [**CS8209**](#void-returning-expression-restrictions): *A value of type 'void' may not be assigned.* - [**CS8310**](#type-binding-for-default-literals-and-typeless-expressions): *Operator 'operator' cannot be applied to operand 'operand'* - [**CS8312**](#type-binding-for-default-literals-and-typeless-expressions): *Use of default literal is not valid in this context* +## Keyword and literal context restrictions + +The following errors arise when keywords or literals are used in contexts where they cannot appear. + +### Base keyword in invalid contexts + +- **CS0175**: *Use of keyword 'base' is not valid in this context* + +The `base` keyword must be used to access a specific member of the base class. It cannot be used as a standalone expression. When you need to reference the base class, access a member explicitly: `base.MemberName` instead of just `base`. + +Common scenarios where this error occurs: + +- Using `base` directly in a method call: `Console.WriteLine(base);` — instead, use `Console.WriteLine(base.Member);` +- Attempting to assign to `base`: `base = value;` — instead, assign to a specific base member: `base.Member = value;` +- Using `base` outside of an instance method in a derived class. + +Ensure you always specify which base class member you need to access. + +### Null in iteration contexts + +- **CS0186**: *Use of null is not valid in this context* + +The `null` literal cannot be used in contexts where the compiler expects a concrete collection or enumerable. This error commonly occurs in `foreach` loops where `null` is provided as the collection to iterate over. + +In a `foreach` loop, the collection must implement `IEnumerable` (or similar interface) and must be non-null. If your data source might be null, check for null before the loop: + +```csharp +IEnumerable collection = /* your source */; +if (collection != null) +{ + foreach (var item in collection) + { + // Process item + } +} +``` + +Alternatively, use a null-coalescing operator or default empty collection: + +```csharp +foreach (var item in collection ?? Enumerable.Empty()) +{ + // Process item +} +``` + +### Void keyword in invalid type contexts + +- **CS1547**: *Keyword 'void' cannot be used in this context* + +The `void` keyword indicates the absence of a return value and cannot be used as a variable type or field type. It is valid only as: + +- A method return type: `void Method() { }` +- A delegate return type: `public delegate void Action();` +- A pointer-to-void in unsafe code: `void* ptr;` + +If you encounter this error, you are likely attempting to declare a variable of type `void`, which is invalid: + +```csharp +// Error: void is not a variable type +void x; +``` + +Instead, choose an appropriate type for the variable. If you need a method that performs an action without returning a value, call it as a standalone statement: + +```csharp +MyMethod(); // Call void method as a statement, don't assign the result +``` + ## Throw expressions in expression contexts - **CS8115**: *A throw expression is not allowed in this context.* diff --git a/docs/csharp/language-reference/toc.yml b/docs/csharp/language-reference/toc.yml index 80c935ad20af8..0de7925feca9c 100644 --- a/docs/csharp/language-reference/toc.yml +++ b/docs/csharp/language-reference/toc.yml @@ -735,6 +735,9 @@ items: - name: Expression-form restrictions href: ./compiler-messages/expression-form-restrictions.md displayName: > + keyword contexts, base keyword, null, void, throw expressions, + declaration expressions, invalid contexts, + CS0175, CS0186, CS1547, CS8115, CS8185, CS8209, CS8310, CS8312 throw expressions, declaration expressions, invalid contexts, CS8115, CS8185, CS8209, CS8310, CS8312 - name: Local functions @@ -996,8 +999,6 @@ items: href: ./compiler-messages/cs0173.md - name: CS0174 href: ../misc/cs0174.md - - name: CS0175 - href: ../misc/cs0175.md - name: CS0176 href: ../misc/cs0176.md - name: CS0177 @@ -1006,8 +1007,6 @@ items: href: ../misc/cs0179.md - name: CS0180 href: ../misc/cs0180.md - - name: CS0186 - href: ../misc/cs0186.md - name: CS0191 href: ../misc/cs0191.md - name: CS0198 @@ -1368,8 +1367,6 @@ items: href: ../misc/cs1542.md - name: CS1545 href: ../misc/cs1545.md - - name: CS1547 - href: ../misc/cs1547.md - name: CS1548 href: ./compiler-messages/cs1548.md - name: CS1551 diff --git a/docs/csharp/misc/cs0175.md b/docs/csharp/misc/cs0175.md deleted file mode 100644 index 929f08a65c6b1..0000000000000 --- a/docs/csharp/misc/cs0175.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -description: "Compiler Error CS0175" -title: "Compiler Error CS0175" -ms.date: 07/20/2015 -f1_keywords: - - "CS0175" -helpviewer_keywords: - - "CS0175" -ms.assetid: cedd769d-8258-4235-a321-362981b9f84b ---- -# Compiler Error CS0175 - -Use of keyword 'base' is not valid in this context - - The [base](../language-reference/keywords/base.md) keyword must be used to specify a particular member of the base class. For more information, see [Constructors](../programming-guide/classes-and-structs/constructors.md). - - The following sample generates CS0175: - -```csharp -// CS0175.cs -using System; -class BaseClass -{ - public int TestInt = 0; -} - -class MyClass : BaseClass -{ - public static void Main() - { - MyClass aClass = new MyClass(); - aClass.BaseTest(); - } - - public void BaseTest() - { - Console.WriteLine(base); // CS0175 - // Try the following line instead: - // Console.WriteLine(base.TestInt); - base = 9; // CS0175 - - // Try the following line instead: - // base.TestInt = 9; - } -} -``` diff --git a/docs/csharp/misc/cs0186.md b/docs/csharp/misc/cs0186.md deleted file mode 100644 index de4e61db1d84a..0000000000000 --- a/docs/csharp/misc/cs0186.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -description: "Compiler Error CS0186" -title: "Compiler Error CS0186" -ms.date: 07/20/2015 -f1_keywords: - - "CS0186" -helpviewer_keywords: - - "CS0186" -ms.assetid: b8afca3e-0fb9-44c5-b4bb-abe3ef134e85 ---- -# Compiler Error CS0186 - -Use of null is not valid in this context - - The following sample generates CS0186: - -```csharp -// CS0186.cs -using System; -using System.Collections; - -class MyClass -{ - static void Main() - { - // Each of the following lines generates CS0186: - foreach (int i in null) {} // CS0186 - foreach (int i in (IEnumerable) null) { }; // CS0186 - } -} -``` diff --git a/docs/csharp/misc/cs1547.md b/docs/csharp/misc/cs1547.md deleted file mode 100644 index 298177d530c65..0000000000000 --- a/docs/csharp/misc/cs1547.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -description: "Compiler Error CS1547" -title: "Compiler Error CS1547" -ms.date: 07/20/2015 -f1_keywords: - - "CS1547" -helpviewer_keywords: - - "CS1547" -ms.assetid: 40029557-076a-47d8-aabc-d86c56a846d7 ---- -# Compiler Error CS1547 - -Keyword 'void' cannot be used in this context - - The compiler detected an invalid use of the [void](../language-reference/builtin-types/void.md) keyword. - - The following sample generates CS1547: - -```csharp -// CS1547.cs -public class MyClass -{ - void BadMethod() - { - void i; // CS1547, cannot have variables of type void - } - - public static void Main() - { - } -} -``` From 7e5253b06a37de6825e2dbb04f272cc480b96946 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Thu, 20 Aug 2026 12:01:36 -0400 Subject: [PATCH 3/6] fix: remove duplicated legacy displayName tail from expression-form TOC entry The displayName folded scalar contained a duplicated five-code tail (CS8115, CS8185, CS8209, CS8310, CS8312 with associated phrases) left over from the original commit after the eight-code expansion appended new content without removing the old suffix. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/csharp/language-reference/toc.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/docs/csharp/language-reference/toc.yml b/docs/csharp/language-reference/toc.yml index 0de7925feca9c..134f4cf632856 100644 --- a/docs/csharp/language-reference/toc.yml +++ b/docs/csharp/language-reference/toc.yml @@ -738,8 +738,6 @@ items: keyword contexts, base keyword, null, void, throw expressions, declaration expressions, invalid contexts, CS0175, CS0186, CS1547, CS8115, CS8185, CS8209, CS8310, CS8312 - throw expressions, declaration expressions, invalid contexts, - CS8115, CS8185, CS8209, CS8310, CS8312 - name: Local functions href: ./compiler-messages/local-function-errors.md displayName: > From 95cffea94a3f66233f18cd8ba6efa7dcd4437a6b Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Thu, 20 Aug 2026 15:01:10 -0400 Subject: [PATCH 4/6] docs: restructure expression-form-restrictions with single H2 section and bullet-point remediation Consolidate five separate H2/H3 subsections into one unified 'Invalid expression contexts' H2 section with scannable bullet-point remediation guidance. All eight diagnostic codes (CS0175, CS0186, CS1547, CS8115, CS8185, CS8209, CS8310, CS8312) now appear as cohesive remedy bullets, preserving all substantive examples and guidance while following prevailing style in delegate-function-pointer-diagnostics.md and foreach-diagnostics.md. Changes: - Removed old H2/H3 headers (Base keyword, Null iteration, Void keyword, Throw expressions, Declaration expressions, Target type required, Void-returning) - Created unified 'Invalid expression contexts' H2 with all anchors consolidated - Restructured master error list to link all codes to single #invalid-expression-contexts - Updated redirects for cs0175.md, cs0186.md, cs1547.md to point to unified anchor - Preserved all code examples, remediation patterns, and guidance from original Validation: 8 codes in front matter, 8 bullet items, 2 code examples, 3 redirects updated, no trailing whitespace, single H2 anchor. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .openpublishing.redirection.csharp.json | 6 +- .../expression-form-restrictions.md | 149 ++++-------------- 2 files changed, 37 insertions(+), 118 deletions(-) diff --git a/.openpublishing.redirection.csharp.json b/.openpublishing.redirection.csharp.json index 3ee9e1a656812..1dbe944505b88 100644 --- a/.openpublishing.redirection.csharp.json +++ b/.openpublishing.redirection.csharp.json @@ -5843,17 +5843,17 @@ }, { "source_path": "docs/csharp/misc/cs0175.md", - "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/expression-form-restrictions#base-keyword-in-invalid-contexts", + "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/expression-form-restrictions#invalid-expression-contexts", "redirect_document_id": "false" }, { "source_path": "docs/csharp/misc/cs0186.md", - "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/expression-form-restrictions#null-in-iteration-contexts", + "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/expression-form-restrictions#invalid-expression-contexts", "redirect_document_id": "false" }, { "source_path": "docs/csharp/misc/cs1547.md", - "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/expression-form-restrictions#void-keyword-in-invalid-type-contexts", + "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/expression-form-restrictions#invalid-expression-contexts", "redirect_document_id": "false" } ] diff --git a/docs/csharp/language-reference/compiler-messages/expression-form-restrictions.md b/docs/csharp/language-reference/compiler-messages/expression-form-restrictions.md index 9fa6ffa9f0628..556baf2605dc1 100644 --- a/docs/csharp/language-reference/compiler-messages/expression-form-restrictions.md +++ b/docs/csharp/language-reference/compiler-messages/expression-form-restrictions.md @@ -31,130 +31,49 @@ This article covers the following compiler errors and warnings: That's by design. The text closely matches the text of the compiler error / warning for SEO purposes. --> -- [**CS0175**](#keyword-and-literal-context-restrictions): *Use of keyword 'base' is not valid in this context* -- [**CS0186**](#keyword-and-literal-context-restrictions): *Use of null is not valid in this context* -- [**CS1547**](#keyword-and-literal-context-restrictions): *Keyword 'void' cannot be used in this context* -- [**CS8115**](#throw-expressions-in-expression-contexts): *A throw expression is not allowed in this context.* -- [**CS8185**](#declaration-expressions-in-restricted-contexts): *A declaration is not allowed in this context.* -- [**CS8209**](#void-returning-expression-restrictions): *A value of type 'void' may not be assigned.* -- [**CS8310**](#type-binding-for-default-literals-and-typeless-expressions): *Operator 'operator' cannot be applied to operand 'operand'* -- [**CS8312**](#type-binding-for-default-literals-and-typeless-expressions): *Use of default literal is not valid in this context* +- [**CS0175**](#invalid-expression-contexts): *Use of keyword 'base' is not valid in this context* +- [**CS0186**](#invalid-expression-contexts): *Use of null is not valid in this context* +- [**CS1547**](#invalid-expression-contexts): *Keyword 'void' cannot be used in this context* +- [**CS8115**](#invalid-expression-contexts): *A throw expression is not allowed in this context.* +- [**CS8185**](#invalid-expression-contexts): *A declaration is not allowed in this context.* +- [**CS8209**](#invalid-expression-contexts): *A value of type 'void' may not be assigned.* +- [**CS8310**](#invalid-expression-contexts): *Operator 'operator' cannot be applied to operand 'operand'* +- [**CS8312**](#invalid-expression-contexts): *Use of default literal is not valid in this context* -## Keyword and literal context restrictions +## Invalid expression contexts -The following errors arise when keywords or literals are used in contexts where they cannot appear. +The following diagnostics identify expressions that appear in contexts where they are not permitted. These errors typically arise when keywords, literals, or expressions are used in positions where the compiler does not permit them. The remediation strategy depends on the specific keyword or expression type. -### Base keyword in invalid contexts +- **CS0175**: *Use of keyword 'base' is not valid in this context*. The `base` keyword must be used to access a specific member of the base class. It cannot be used as a standalone expression. When you need to reference the base class, access a member explicitly: `base.MemberName` instead of just `base`. For example, avoid `Console.WriteLine(base);` and instead use `Console.WriteLine(base.Member);`. Similarly, do not attempt to assign to `base` directly; instead, assign to a specific base member: `base.Member = value;`. Ensure you always specify which base class member you need to access. This error also occurs when using `base` outside of an instance method in a derived class. -- **CS0175**: *Use of keyword 'base' is not valid in this context* +- **CS0186**: *Use of null is not valid in this context*. The `null` literal cannot be used in contexts where the compiler expects a concrete collection or enumerable. This error commonly occurs in `foreach` loops where `null` is provided as the collection to iterate over. In a `foreach` loop, the collection must implement `IEnumerable` (or similar interface) and must be non-null. If your data source might be null, check for null before the loop: -The `base` keyword must be used to access a specific member of the base class. It cannot be used as a standalone expression. When you need to reference the base class, access a member explicitly: `base.MemberName` instead of just `base`. + ```csharp + IEnumerable collection = /* your source */; + if (collection != null) + { + foreach (var item in collection) + { + // Process item + } + } + ``` -Common scenarios where this error occurs: + Alternatively, use a null-coalescing operator or default empty collection: -- Using `base` directly in a method call: `Console.WriteLine(base);` — instead, use `Console.WriteLine(base.Member);` -- Attempting to assign to `base`: `base = value;` — instead, assign to a specific base member: `base.Member = value;` -- Using `base` outside of an instance method in a derived class. + ```csharp + foreach (var item in collection ?? Enumerable.Empty()) + { + // Process item + } + ``` -Ensure you always specify which base class member you need to access. +- **CS1547**: *Keyword 'void' cannot be used in this context*. The `void` keyword indicates the absence of a return value and cannot be used as a variable type or field type. It is valid only as a method return type (`void Method() { }`), a delegate return type (`public delegate void Action();`), or a pointer-to-void in unsafe code (`void* ptr;`). If you encounter this error, you are likely attempting to declare a variable of type `void`, which is invalid. Instead, choose an appropriate type for the variable. If you need a method that performs an action without returning a value, call it as a standalone statement (`MyMethod();`); do not attempt to assign its result. -### Null in iteration contexts +- **CS8115**: *A throw expression is not allowed in this context.*. The compiler permits throw expressions only in specific contexts where an expression can appear and the exception is immediately propagated. Move the `throw` expression to a valid context, such as a conditional arm of a ternary or switch expression (where the throw is one of the arms), an assignment to evaluate the throw in place of the assigned value, or an argument to a method call where throwing is appropriate. A throw expression can also appear in a statement in a lambda or local function body (not within a method that must return a value). If the throw expression appears in a position where the expression value must be used (such as within arithmetic or operator expressions), extract it into a separate statement or conditional check. -- **CS0186**: *Use of null is not valid in this context* +- **CS8185**: *A declaration is not allowed in this context.*. The compiler permits declaration expressions (`out var`, pattern-matching declarations) only in specific positions, including `out` parameter declarations in method calls and in certain statement contexts. Remove the declaration expression from contexts where it's not permitted, such as lambda expression bodies (unless the lambda is a statement body), query expressions where the grammar forbids declarations, inside attribute arguments, or in contexts that require a read-only expression. If you need to use an out variable, call the method in a separate statement, then reference the resulting variable. Alternatively, use a local variable declaration before the expression. -The `null` literal cannot be used in contexts where the compiler expects a concrete collection or enumerable. This error commonly occurs in `foreach` loops where `null` is provided as the collection to iterate over. +- **CS8209**: *A value of type 'void' may not be assigned.*. The `void` type is not a value type; it represents the absence of a return value. Remove the assignment of void-returning expressions. If you need to invoke a method that returns `void`, call it as a standalone statement. If you need a result, use a method that returns a value instead. Ensure that expressions assigned to variables always have a meaningful return type. -In a `foreach` loop, the collection must implement `IEnumerable` (or similar interface) and must be non-null. If your data source might be null, check for null before the loop: - -```csharp -IEnumerable collection = /* your source */; -if (collection != null) -{ - foreach (var item in collection) - { - // Process item - } -} -``` - -Alternatively, use a null-coalescing operator or default empty collection: - -```csharp -foreach (var item in collection ?? Enumerable.Empty()) -{ - // Process item -} -``` - -### Void keyword in invalid type contexts - -- **CS1547**: *Keyword 'void' cannot be used in this context* - -The `void` keyword indicates the absence of a return value and cannot be used as a variable type or field type. It is valid only as: - -- A method return type: `void Method() { }` -- A delegate return type: `public delegate void Action();` -- A pointer-to-void in unsafe code: `void* ptr;` - -If you encounter this error, you are likely attempting to declare a variable of type `void`, which is invalid: - -```csharp -// Error: void is not a variable type -void x; -``` - -Instead, choose an appropriate type for the variable. If you need a method that performs an action without returning a value, call it as a standalone statement: - -```csharp -MyMethod(); // Call void method as a statement, don't assign the result -``` - -## Throw expressions in expression contexts - -- **CS8115**: *A throw expression is not allowed in this context.* - -The compiler permits throw expressions only in specific contexts where an expression can appear and the exception is immediately propagated. Move the `throw` expression to a valid context, such as: - -- A conditional arm of a ternary or switch expression (where the throw is one of the arms). -- An assignment to evaluate the throw in place of the assigned value. -- An argument to a method call where throwing is appropriate. -- A statement in a lambda or local function body (not within a method that must return a value). - -If the throw expression appears in a position where the expression value must be used (such as within arithmetic or operator expressions), extract it into a separate statement or conditional check. - -## Declaration expressions in restricted contexts - -- **CS8185**: *A declaration is not allowed in this context.* - -The compiler permits declaration expressions (`out var`, pattern-matching declarations) only in specific positions. These include `out` parameter declarations in method calls and in certain statement contexts. Remove the declaration expression from contexts where it's not permitted, such as: - -- Lambda expression bodies (unless the lambda is a statement body). -- Query expressions where the grammar forbids declarations. -- Inside attribute arguments. -- In contexts that require a read-only expression. - -If you need to use an out variable, call the method in a separate statement, then reference the resulting variable. Alternatively, use a local variable declaration before the expression. - -## Type binding for default literals and typeless expressions - -- **CS8310**: *Operator 'operator' cannot be applied to operand 'operand'* -- **CS8312**: *Use of default literal is not valid in this context* - -The `default` literal and typeless expressions (such as `null` or `new` without a target type) require a target type for the compiler to infer the expression type. When an operator is applied to these expressions without enough context, the compiler cannot determine the operand type. - -Provide the target type by: - -- Adding an explicit type cast: `(int)default` or `(MyType)new`. -- Assigning to a typed variable: `int x = default;`. -- Using a method parameter or return type to establish context. -- Using the verbose form `default(Type)` instead of the `default` literal for clarity. - -If the operator itself requires a specific type, ensure the operand can be implicitly converted to that type. - -## Void-returning expression restrictions - -- **CS8209**: *A value of type 'void' may not be assigned.* - -The `void` type is not a value type; it represents the absence of a return value. Remove the assignment of void-returning expressions. If you need to invoke a method that returns `void`, call it as a standalone statement. If you need a result, use a method that returns a value instead. - -Ensure that expressions assigned to variables always have a meaningful return type. +- **CS8310**: *Operator 'operator' cannot be applied to operand 'operand'* and **CS8312**: *Use of default literal is not valid in this context*. The `default` literal and typeless expressions (such as `null` or `new` without a target type) require a target type for the compiler to infer the expression type. When an operator is applied to these expressions without enough context, the compiler cannot determine the operand type. Provide the target type by adding an explicit type cast (`(int)default` or `(MyType)new`), assigning to a typed variable (`int x = default;`), using a method parameter or return type to establish context, or using the verbose form `default(Type)` instead of the `default` literal for clarity. If the operator itself requires a specific type, ensure the operand can be implicitly converted to that type. From b7d161ba25bdee1ebad152236299651147712683 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Thu, 20 Aug 2026 16:34:02 -0400 Subject: [PATCH 5/6] Proofread and finalize. --- .../expression-form-restrictions.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/csharp/language-reference/compiler-messages/expression-form-restrictions.md b/docs/csharp/language-reference/compiler-messages/expression-form-restrictions.md index 556baf2605dc1..5c7ed09e84e83 100644 --- a/docs/csharp/language-reference/compiler-messages/expression-form-restrictions.md +++ b/docs/csharp/language-reference/compiler-messages/expression-form-restrictions.md @@ -27,8 +27,8 @@ ai-usage: ai-assisted This article covers the following compiler errors and warnings: - - [**CS0175**](#invalid-expression-contexts): *Use of keyword 'base' is not valid in this context* @@ -42,11 +42,11 @@ That's by design. The text closely matches the text of the compiler error / warn ## Invalid expression contexts -The following diagnostics identify expressions that appear in contexts where they are not permitted. These errors typically arise when keywords, literals, or expressions are used in positions where the compiler does not permit them. The remediation strategy depends on the specific keyword or expression type. +The following diagnostics identify expressions that appear in contexts where they're not permitted. These errors typically arise when you use keywords, literals, or expressions in positions where the compiler doesn't permit them. The remediation strategy depends on the specific keyword or expression type. -- **CS0175**: *Use of keyword 'base' is not valid in this context*. The `base` keyword must be used to access a specific member of the base class. It cannot be used as a standalone expression. When you need to reference the base class, access a member explicitly: `base.MemberName` instead of just `base`. For example, avoid `Console.WriteLine(base);` and instead use `Console.WriteLine(base.Member);`. Similarly, do not attempt to assign to `base` directly; instead, assign to a specific base member: `base.Member = value;`. Ensure you always specify which base class member you need to access. This error also occurs when using `base` outside of an instance method in a derived class. +- **CS0175**: *Use of keyword 'base' is not valid in this context*. Use the `base` keyword to access a specific member of the base class. Don't use it as a standalone expression. When you need to reference the base class, access a member explicitly: `base.MemberName` instead of just `base`. For example, avoid `Console.WriteLine(base);` and instead use `Console.WriteLine(base.Member);`. Similarly, don't attempt to assign to `base` directly; instead, assign to a specific base member: `base.Member = value;`. Ensure you always specify which base class member you need to access. This error also occurs when using `base` outside of an instance method in a derived class. -- **CS0186**: *Use of null is not valid in this context*. The `null` literal cannot be used in contexts where the compiler expects a concrete collection or enumerable. This error commonly occurs in `foreach` loops where `null` is provided as the collection to iterate over. In a `foreach` loop, the collection must implement `IEnumerable` (or similar interface) and must be non-null. If your data source might be null, check for null before the loop: +- **CS0186**: *Use of null is not valid in this context*. You can't use the `null` literal in contexts where the compiler expects a concrete collection or enumerable. This error commonly occurs in `foreach` loops where `null` is provided as the collection to iterate over. In a `foreach` loop, the collection must implement `IEnumerable` (or similar interface) and must be non-null. If your data source might be null, check for null before the loop: ```csharp IEnumerable collection = /* your source */; @@ -68,12 +68,12 @@ The following diagnostics identify expressions that appear in contexts where the } ``` -- **CS1547**: *Keyword 'void' cannot be used in this context*. The `void` keyword indicates the absence of a return value and cannot be used as a variable type or field type. It is valid only as a method return type (`void Method() { }`), a delegate return type (`public delegate void Action();`), or a pointer-to-void in unsafe code (`void* ptr;`). If you encounter this error, you are likely attempting to declare a variable of type `void`, which is invalid. Instead, choose an appropriate type for the variable. If you need a method that performs an action without returning a value, call it as a standalone statement (`MyMethod();`); do not attempt to assign its result. +- **CS1547**: *Keyword 'void' cannot be used in this context*. The `void` keyword indicates the absence of a return value and can't be used as a variable type or field type. It's valid only as a method return type (`void Method() { }`), a delegate return type (`public delegate void Action();`), or a pointer-to-void in unsafe code (`void* ptr;`). If you encounter this error, you're likely attempting to declare a variable of type `void`, which is invalid. Instead, choose an appropriate type for the variable. If you need a method that performs an action without returning a value, call it as a standalone statement (`MyMethod();`); don't attempt to assign its result. - **CS8115**: *A throw expression is not allowed in this context.*. The compiler permits throw expressions only in specific contexts where an expression can appear and the exception is immediately propagated. Move the `throw` expression to a valid context, such as a conditional arm of a ternary or switch expression (where the throw is one of the arms), an assignment to evaluate the throw in place of the assigned value, or an argument to a method call where throwing is appropriate. A throw expression can also appear in a statement in a lambda or local function body (not within a method that must return a value). If the throw expression appears in a position where the expression value must be used (such as within arithmetic or operator expressions), extract it into a separate statement or conditional check. - **CS8185**: *A declaration is not allowed in this context.*. The compiler permits declaration expressions (`out var`, pattern-matching declarations) only in specific positions, including `out` parameter declarations in method calls and in certain statement contexts. Remove the declaration expression from contexts where it's not permitted, such as lambda expression bodies (unless the lambda is a statement body), query expressions where the grammar forbids declarations, inside attribute arguments, or in contexts that require a read-only expression. If you need to use an out variable, call the method in a separate statement, then reference the resulting variable. Alternatively, use a local variable declaration before the expression. -- **CS8209**: *A value of type 'void' may not be assigned.*. The `void` type is not a value type; it represents the absence of a return value. Remove the assignment of void-returning expressions. If you need to invoke a method that returns `void`, call it as a standalone statement. If you need a result, use a method that returns a value instead. Ensure that expressions assigned to variables always have a meaningful return type. +- **CS8209**: *A value of type 'void' may not be assigned.*. The `void` type isn't a value type; it represents the absence of a return value. Remove the assignment of void-returning expressions. If you need to invoke a method that returns `void`, call it as a standalone statement. If you need a result, use a method that returns a value instead. Ensure that expressions assigned to variables always have a meaningful return type. -- **CS8310**: *Operator 'operator' cannot be applied to operand 'operand'* and **CS8312**: *Use of default literal is not valid in this context*. The `default` literal and typeless expressions (such as `null` or `new` without a target type) require a target type for the compiler to infer the expression type. When an operator is applied to these expressions without enough context, the compiler cannot determine the operand type. Provide the target type by adding an explicit type cast (`(int)default` or `(MyType)new`), assigning to a typed variable (`int x = default;`), using a method parameter or return type to establish context, or using the verbose form `default(Type)` instead of the `default` literal for clarity. If the operator itself requires a specific type, ensure the operand can be implicitly converted to that type. +- **CS8310**: *Operator 'operator' cannot be applied to operand 'operand'* and **CS8312**: *Use of default literal is not valid in this context*. The `default` literal and typeless expressions (such as `null` or `new` without a target type) require a target type for the compiler to infer the expression type. When an operator is applied to these expressions without enough context, the compiler can't determine the operand type. Provide the target type by adding an explicit type cast (`(int)default` or `(MyType)new`), assigning to a typed variable (`int x = default;`), using a method parameter or return type to establish context, or using the verbose form `default(Type)` instead of the `default` literal for clarity. If the operator itself requires a specific type, ensure the operand can be implicitly converted to that type. From 51b5db327cb1cc8d073ba6edcc3c8fd51ed1a21d Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Thu, 20 Aug 2026 17:01:12 -0400 Subject: [PATCH 6/6] Update docs/csharp/language-reference/compiler-messages/expression-form-restrictions.md Co-authored-by: Genevieve Warren <24882762+gewarren@users.noreply.github.com> --- .../compiler-messages/expression-form-restrictions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/csharp/language-reference/compiler-messages/expression-form-restrictions.md b/docs/csharp/language-reference/compiler-messages/expression-form-restrictions.md index 5c7ed09e84e83..160eb65ae9214 100644 --- a/docs/csharp/language-reference/compiler-messages/expression-form-restrictions.md +++ b/docs/csharp/language-reference/compiler-messages/expression-form-restrictions.md @@ -1,6 +1,6 @@ --- title: "Resolve errors from invalid expression contexts" -description: "This article helps you diagnose and correct compiler errors and warnings from expressions that appear in contexts where they are not permitted" +description: "This article helps you diagnose and correct C# compiler errors and warnings from expressions that appear in contexts where they are not permitted" f1_keywords: - "CS0175" - "CS0186"