[Proposal] Collection expressions for custom types should call a constructor that takes an int, if possible #8302
Unanswered
BlinD-HuNTeR
asked this question in
Language Ideas
Replies: 2 comments 1 reply
-
There was discussion about this - I don't remember whether it was LDM notes or elsewhere - and they looked into generalizing this and decided against it for now. They considered just |
Beta Was this translation helpful? Give feedback.
0 replies
-
If we were to do this, we'd require the parameter to be called |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
One of the nice features of collection expressions is the "known length", when the compiler knows the total number of elements in advance, it can use that information to preallocate the resulting storage and avoid reallocations.
But currently this feature works only with the builtin types, you can't construct a custom collection type that takes advantage of it.
The following example demonstrates this:
My proposal is that, for types implementing the IEnumerable/Add pattern, collection expressions could also look for a constructor that takes an int, and if the length is known, that constructor will be invoked with the known length.
Another cool consequence of this, is that it will be possible for someone to make a collection type that only exposes the
int
constructor, and the result is that, such a collection will only be constructible when the length is known. I suppose this could be nice for perf-oriented projects (Roslyn?), to force the developers to write code that avoids reallocations, as it would not compile.Beta Was this translation helpful? Give feedback.
All reactions