Closed as not planned
Closed as not planned
Description
Background and motivation
I'd like to request the ability to subclass arrays or define custom array-like types with the performance and syntax of native arrays ([]). This would enable scenarios where custom logic, metadata, or behavior is tied directly to the array structure itself, rather than using wrappers or parallel structures.
Motivation:
Currently, arrays in C# are sealed and cannot be extended. While System.Array is an abstract class, it is not possible to derive from it in user code. This limits the extensibility of array-like behavior. For example:
- Attaching metadata or custom indexing behavior to an array.
- Implementing bounds checking, logging, or change tracking directly in an array.
- Supporting custom memory layouts for high-performance scenarios.
Workarounds involve wrapping arrays in custom classes, which:
- Adds an extra layer of indirection.
- Breaks compatibility with APIs expecting T[].
- Loses the syntactic and performance benefits of raw arrays.
API Proposal
public class CustomArray<T> : System.Array
{
// ..custom data and implementation
}
API Usage
public class CustomArray<T> : System.Array
{
}
var c = new CustomArray<string>(32);
c[0] = "Hello";
string[] other = c;
Console.WriteLine(other[0]); // should print "Hello"
Alternative Designs
A dynamically (or statically) sized inlined array, syntax can be determined later.
public class CustomArray<T>
{
// not sure how to plug a variable for determining the size of the array
public ref int[] MyCustomInlinedArray; // not possible to store into int[] reference
}
var c = new CustomArray<string>(32);
c.MyCustomInlinedArray[0] = "Hello World";
var span = c.MyCustomInlinedArray.AsSpan();
Risks
No response