-
Notifications
You must be signed in to change notification settings - Fork 4.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[API Proposal]: ImmutableArray<T>.Builder.ToImmutableAndClear()
#72625
Comments
Tagging subscribers to this area: @dotnet/area-system-collections Issue DetailsBackground and motivationIn basically every project I use API Proposalnamespace System.Collections.Immutable;
public struct ImmutableArray<T>
{
public class Builder
{
public ImmutableArray<T> ToImmutableAndClear()
{
if (Capacity == Count) return MoveToImmutable();
else
{
var result = ToImmutable();
Clear();
return result;
}
}
}
} API Usagevar builder = ImmutableArray.CreateBuilder<string>(/* max possible values */ 42);
foreach (var x in thingGettingMapped)
{
if (x.Frob) builder.Add(x);
}
return builder.ToImmutableAndFree(); Alternative DesignsNo response RisksNo response
|
I also use something like this quite often in my generators and would very much welcome this API 🙂 Nit: the proposal says |
No, force of habit. Roslyn also pools builders. |
Sounds useful enough. If we do add such a method, we might want to explicitly document that any perf benefits are predicated on |
The challenge is that namespace System.Collections.Immutable;
public partial struct ImmutableArray<T>
{
public partial class Builder
{
public ImmutableArray<T> ToImmutableAndClear();
}
} |
namespace System.Collections.Immutable;
public struct ImmutableArray<T>
{
public partial class Builder
{
public ImmutableArray<T> DrainToImmutable();
}
} |
Background and motivation
In basically every project I use
ImmutableArray
in, I end up creating an extension forToImmutableAndClear
on the builder type, which takes advantage ofMoveToImmutable()
if the current builder has right size, and otherwise falls back toToImmutable()/Clear()
if not. I would really love it if we added this to the BCL itself.API Proposal
API Usage
Alternative Designs
No response
Risks
No response
The text was updated successfully, but these errors were encountered: