Range Over Channels in C#
Our example demonstrates how to iterate over values received from a channel. In C#, we’ll use a BlockingCollection<T>
to simulate a similar behavior.
When you run this program, you’ll see:
This example also shows that it’s possible to complete adding to a non-empty collection but still have the remaining values be received.
In C#, we use a BlockingCollection<T>
to simulate a channel-like behavior. The BlockingCollection<T>
class provides blocking and bounding capabilities, which are similar to Go’s buffered channels.
Here’s a breakdown of the C# code:
We create a
BlockingCollection<string>
with a capacity of 2, similar to the buffered channel in the original example.We add two items to the collection using the
Add
method.We call
CompleteAdding()
to signal that no more items will be added to the collection. This is similar to closing a channel in Go.We use a
foreach
loop withGetConsumingEnumerable()
to iterate over the items in the collection. This method will block if the collection is empty and will stop when the collection is empty andCompleteAdding()
has been called.Inside the loop, we print each element, just like in the original example.
This C# code provides similar functionality to the Go example, demonstrating how to iterate over a collection that behaves like a channel.