You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[API Proposal]: Array.Create<T> with default value and factory function #121477
There is currently no direct, concise way to create an array of a given size and initialize all its elements with either a specific default value or the result of a factory function. This is a safer approach when using non-nullable types or value types with an invalid default value.
API Proposal
namespaceSystem;publicstaticclassArray{// Creates a new array of the specified length, filled with the given valuepublicstaticT[]Create<T>(intlength,Tvalue);// Creates a new array of the specified length, initializing each element with the result of a factory functionpublicstaticT[]Create<T>(intlength,Func<int,T>factory);}
API Usage
// Fill an array with a constant value:int[]tens=Array.Create<int>(5,10);// [10, 10, 10, 10, 10]// Fill with custom factory values:string[]str=Array.Create<string>(3, i =>$"Value {i}");// ["Value 0", "Value 1", "Value 2"]// Fill a struct array with a default struct instance:MyStruct[]structs=Array.Create(8,newMyStruct());// Advanced: Fill with different objectsobject[]objects=Array.Create(4, i =>newobject());
Alternative Designs
Using Enumerable.Repeat or Enumerable.Range(...).Select(...).ToArray(), though these incur more overhead and do not directly result in T[], especially for arrays
Use of manual loops with for (var i = 0; i < length; ++i)
Extension static
Risks
Could introduce confusion with existing ways to create and initialize arrays
Needs care to avoid performance regressions compared to manual loop
API shape must not conflict with other Array.Create overloads
Reacted by rampaa, saint4eva, Cole Tobin and Joni Aromaa
This would be beneficial for NRT's IF this was coupled with analyzer / language feature that enforces array initialization on creation, something akin to Kotlin.
Currently the following snipped gives no indication whatsoever to the developer that there is something wrong.
string[]wow=newstring[100];stringa=wow[0];// null
Reacted by rampaa, Cole Tobin and Govert van Drimmelen
Do you have a real-world code example where it would make a difference?
I think most of the real world examples can use or are likely to already be using GC.AllocateUninitializedArray. I expect some could switch over to Create(size, value) but likely wouldn't be able to switch over to Create(size, factory) due to the delegate overhead and lack of good inlining support (for delegates) that exists today
That being said, I would expect that this or a similar helper for stack based allocations (which the JIT then understood) could have measurable impact across an entire app, particularly for large scale and long running services and especially if it was something that Roslyn and the core libraries could implicitly take advantage of behind the scenes. All the separate 10-100 item allocations do add up and that can be a significant amount of memory that ends up being double zeroed. For large scale services, even 0.1% can be a significant savings per year.
I think this conversation sums up the value of the api and the reasons why it hasn’t been added yet.
Saving one call doesn’t seem like much, but the alternative API pair requires two statements. This is annoying in expression contexts because you can’t use statements. For example, in a field initializer you’re forced to extract to either a constructor or method.
The zero skipping doesn’t seem like it saves much for small arrays. I’d like to do a benchmark to figure out where the tipping point is. I can think of some examples of potentially large arrays where this could help: creating a bunch of random data for a Monte Carlo simulation, initializing all edges to infinity in a graph search algorithm with edge cost, or initializing weights in a neural network. None of these are every day activities.
Finally, the non-nullable scenario is currently skipped by nullable analysis, so the problem slides under the radar.
If it were just one of these things I don’t think this API is worth taking, but collectively it seems to solve a lot of paper cuts.
Reacted by Tanner Gooding, rampaa, Ryan Buckley and Cole Tobin
@bartonjs Missed this live but had a question during my watch. Are there any guidelines about overloads that only replace a generic type argument with a delegate? I'm thinking of this (very) niche case:
// I actually want to fill with Funcs, so CreateFilled<T>(int length, T value) is calledvarx=Array.CreateFilled(10,(inti,intj)=>i+j);// I change my Func signature, but now CreateFilled<T>(int length, Func<int, T> factory) is called insteadvarx=Array.CreateFilled(10,(inti)=>i+3);// unless I name the argument
would fail to compile at the line containing the error, rather than later when someone was using the array that had the wrong type.
If common cases would set it off, that's something we try designing around, but I think you have to admit the edge case not the most likely... and since it has a stylistic workaround, it's not something we'd want to break the method group into two groups for.
I do not expect we will add the approved unless there is evidence that it is actually useful. This can stay closed until such evidence materializes. And once that happens, the actually useful overload is likely going to have a different signature than the approved one.
Activity
dotnet-policy-service commentedon Nov 9, 2025
Tagging subscribers to this area: @dotnet/area-system-collections
See info in area-owners.md if you want to be subscribed.
dotnet-policy-service commentedon Nov 9, 2025
Tagging subscribers to this area: @dotnet/area-system-runtime
See info in area-owners.md if you want to be subscribed.
dotnet-policy-service commentedon Nov 9, 2025
Tagging subscribers to this area: @dotnet/area-system-collections
See info in area-owners.md if you want to be subscribed.
dotnet-policy-service commentedon Nov 9, 2025
Tagging subscribers to this area: @dotnet/area-system-runtime
See info in area-owners.md if you want to be subscribed.
stephentoub commentedon Nov 9, 2025
What's the benefit of:
over:
? Just that it's one expression instead of two statements?
agocke commentedon Nov 9, 2025
I think we can make it faster by allocating an uninitialized array, then filling
jkotas commentedon Nov 10, 2025
It will make a difference only for large arrays.
Do you have a real-world code example where it would make a difference?
aromaa commentedon Nov 10, 2025
This would be beneficial for NRT's IF this was coupled with analyzer / language feature that enforces array initialization on creation, something akin to Kotlin.
Currently the following snipped gives no indication whatsoever to the developer that there is something wrong.
tannergooding commentedon Nov 10, 2025
I think most of the real world examples can use or are likely to already be using
GC.AllocateUninitializedArray. I expect some could switch over toCreate(size, value)but likely wouldn't be able to switch over toCreate(size, factory)due to the delegate overhead and lack of good inlining support (for delegates) that exists todayThat being said, I would expect that this or a similar helper for stack based allocations (which the JIT then understood) could have measurable impact across an entire app, particularly for large scale and long running services and especially if it was something that Roslyn and the core libraries could implicitly take advantage of behind the scenes. All the separate 10-100 item allocations do add up and that can be a significant amount of memory that ends up being double zeroed. For large scale services, even 0.1% can be a significant savings per year.
agocke commentedon Nov 10, 2025
I think this conversation sums up the value of the api and the reasons why it hasn’t been added yet.
Saving one call doesn’t seem like much, but the alternative API pair requires two statements. This is annoying in expression contexts because you can’t use statements. For example, in a field initializer you’re forced to extract to either a constructor or method.
The zero skipping doesn’t seem like it saves much for small arrays. I’d like to do a benchmark to figure out where the tipping point is. I can think of some examples of potentially large arrays where this could help: creating a bunch of random data for a Monte Carlo simulation, initializing all edges to infinity in a graph search algorithm with edge cost, or initializing weights in a neural network. None of these are every day activities.
Finally, the non-nullable scenario is currently skipped by nullable analysis, so the problem slides under the radar.
If it were just one of these things I don’t think this API is worth taking, but collectively it seems to solve a lot of paper cuts.
7 remaining items
dotnet-policy-service commentedon Aug 17, 2026
Tagging subscribers to this area: @dotnet/area-system-runtime
See info in area-owners.md if you want to be subscribed.
bartonjs commentedon Sep 1, 2026
Video
EvanMulawski commentedon Sep 1, 2026
@bartonjs Missed this live but had a question during my watch. Are there any guidelines about overloads that only replace a generic type argument with a delegate? I'm thinking of this (very) niche case:
Curious if this applies here:
agocke commentedon Sep 1, 2026
I believe you can solve that case by manually providing the type arguments
bartonjs commentedon Sep 1, 2026
As @agocke says, that could be solved by specifying the generic:
And, like most things, would be improved by not using
var😁, sincewould fail to compile at the line containing the error, rather than later when someone was using the array that had the wrong type.
If common cases would set it off, that's something we try designing around, but I think you have to admit the edge case not the most likely... and since it has a stylistic workaround, it's not something we'd want to break the method group into two groups for.
Array.Create<T> with default value (#134745)
AustinWise commentedon Oct 12, 2026
This should be reopened since the approved overload that takes a
Func<int, T>was not added in the #134745.jkotas commentedon Oct 12, 2026
I do not expect we will add the approved unless there is evidence that it is actually useful. This can stay closed until such evidence materializes. And once that happens, the actually useful overload is likely going to have a different signature than the approved one.