From a4792c9a7f4a064682a6a11bca1211085a93944f Mon Sep 17 00:00:00 2001 From: Charles Stoner <10732005+cston@users.noreply.github.com> Date: Wed, 1 May 2024 11:59:42 -0700 Subject: [PATCH] Document breaking change: Collection expression for type implementing IEnumerable must have elements implicitly convertible to object (#73278) --- .../Compiler Breaking Changes - DotNet 8.md | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/docs/compilers/CSharp/Compiler Breaking Changes - DotNet 8.md b/docs/compilers/CSharp/Compiler Breaking Changes - DotNet 8.md index 76b8741267d6e..351e636ac80db 100644 --- a/docs/compilers/CSharp/Compiler Breaking Changes - DotNet 8.md +++ b/docs/compilers/CSharp/Compiler Breaking Changes - DotNet 8.md @@ -28,6 +28,34 @@ public class C } ``` +## Collection expression for type implementing `IEnumerable` must have elements implicitly convertible to `object` + +***Introduced in Visual Studio 2022 version 17.10*** + +*Conversion* of a collection expression to a `struct` or `class` that implements `System.Collections.IEnumerable` and *does not* have a strongly-typed `GetEnumerator()` +requires the elements in the collection expression are implicitly convertible to the `object`. +Previously, the elements of a collection expression targeting an `IEnumerable` implementation were assumed to be convertible to `object`, and converted only when binding to the applicable `Add` method. + +This additional requirement means that collection expression conversions to `IEnumerable` implementations are treated consistently with other target types where the elements in the collection expression must be implicitly convertible to the *iteration type* of the target type. + +This change affects collection expressions targeting `IEnumerable` implementations where the elements rely on target-typing to a strongly-typed `Add` method parameter type. +In the example below, an error is reported that `_ => { }` cannot be implicitly converted to `object`. +```csharp +class Actions : IEnumerable +{ + public void Add(Action action); + // ... +} + +Actions a = [_ => { }]; // error CS8917: The delegate type could not be inferred. +``` + +To resolve the error, the element expression could be explicitly typed. +```csharp +a = [(int _) => { }]; // ok +a = [(Action)(_ => { })]; // ok +``` + ## Collection expression target type must have constructor and `Add` method ***Introduced in Visual Studio 2022 version 17.10***