Create empty IAsyncEnumerable
If you install the System.Linq.Async
package, you should be able to use AsyncEnumable.Empty<string>()
. Here's a complete example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
IAsyncEnumerable<string> empty = AsyncEnumerable.Empty<string>();
var count = await empty.CountAsync();
Console.WriteLine(count); // Prints 0
}
}
If for any reason you don't want to install the package which is mentioned in Jon's answer, you can create the method AsyncEnumerable.Empty<T>()
like this:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public static class AsyncEnumerable
{
public static IAsyncEnumerator<T> Empty<T>() => EmptyAsyncEnumerator<T>.Instance;
class EmptyAsyncEnumerator<T> : IAsyncEnumerator<T>
{
public static readonly EmptyAsyncEnumerator<T> Instance =
new EmptyAsyncEnumerator<T>();
public T Current => default!;
public ValueTask DisposeAsync() => default;
public ValueTask<bool> MoveNextAsync() => new ValueTask<bool>(false);
}
}
Note: The answer doesn't discourage using the System.Linq.Async
package. This answer provides a brief implementation of AsyncEnumerable.Empty<T>()
for cases that you need it and you cannot/don't want to use the package. You can find the implementation used in the package here.