Enable the use of Collection Expressions in IAsyncEnumerables. #112761
-
I was going to create a new API proposal for this but I realized that I'm not exactly sure what the API design would look like, so I'm making this a discussion instead. Currently, collection expression initializers ( namespace System.Collections.Generic;
public sealed class FileService
{
public IAsyncEnumerable<string> EnumerateLines(string filePath)
{
ArgumentException.ThrowIfNullOrWhiteSpace(filePath);
FileInfo file = new(filePath);
if (file is { Exists: false } or { Length: 0 })
{
return []; // CS9174: Cannot initialize type 'IAsyncEnumerable<string>' with a collection expression because the type is not constructable.
}
return EnumerateCore(file);
}
} While the error is entirely correct (you cannot construct an instance of an interface), the exact same code works in a synchronous context. namespace System.Collections.Generic;
public sealed class FileService
{
public IEnumerable<string> EnumerateLines(string filePath)
{
ArgumentException.ThrowIfNullOrWhiteSpace(filePath);
FileInfo file = new(filePath);
if (file is { Exists: false } or { Length: 0 })
{
return []; // No error!
}
return EnumerateCore(file);
}
} I would expect that this behavior should work regardless of whether you're using Currently, developers are required to return a concrete type. There are currently three options availble to them:
Edit: It seems there is an upcoming fourth option. C# 10 Preview 1 has added several methods for working with AsyncEnumerable directly to the base LINQ library. This should allow for a solution like option 1, but without additional dependencies. |
Beta Was this translation helpful? Give feedback.
#111715