dotnet / dotnet/runtime

[API Proposal]: Array.Create<T> with default value and factory function

Open
#121,477 16 comments 4 reactions 0 assignees View on GitHub
api-approved area-System.Runtime tenet-performance
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

### Background and motivation

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

```csharp
namespace System;

public static class Array
{
// Creates a new array of the specified length, filled with the given value
public static T[] Create(int length, T value);

// Creates a new array of the specified length, initializing each element with the result of a factory function
public static T[] Create(int length, Func factory);
}
```

### API Usage

```csharp
// Fill an array with a constant value:
int[] tens = Array.Create(5, 10); // [10, 10, 10, 10, 10]

// Fill with custom factory values:
string[] str = Array.Create(3, i => $"Value {i}"); // ["Value 0", "Value 1", "Value 2"]

// Fill a struct array with a default struct instance:
MyStruct[] structs = Array.Create(8, new MyStruct());

// Advanced: Fill with different objects
object[] objects = Array.Create(4, i => new object());
```

### 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

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.