dotnet / dotnet/runtime

[API Proposal]: Span<T> overloads for ICollection<T>

Open
#120,446 2 comments 1 reaction 0 assignees View on GitHub
api-suggestion area-System.Collections
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

### Background and motivation

Adding these overloads would make copying temporary data more memory efficient, as this will allow copying it into stack-allocated buffers, for example, when temporarily copying keys to remove some values from a dictionary several times per frame.

### API Proposal

```diff
namespace System.Collections.Generic
{
public interface ICollection : IEnumerable
{
+ void CopyTo(Span destination);
+ bool TryCopyTo(Span destination);
}
}
```

### API Usage

```csharp
// Initialize a dictionary
Dictionary catalog = new Dictionary
{
["apple"] = 10,
["juice"] = 19
};

// Copy keys to a span
Span items = new string[catalog.Count];
catalog.Keys.CopyTo(items);

// Copy values to a span
Span prices = stackalloc int[catalog.Count];
catalog.Values.CopyTo(prices);

// Try to copy values only to a specific region
int[] pricesRegion = new int[prices.Count * 2];
if (!catalog.Values.TryCopyTo(pricesRegion.AsSpan(1, catalog.Count / 2)))
{
Array.Fill(pricesRegion, -1, 1, prices.Count / 2);
}
```

### Alternative Designs

_No response_

### Risks

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.