Skip to content

Proposal: Generic overloads of Array.Copy #18497

Description

@jamesqo

Background

There are a lot of static Array methods that have generic overloads. Take for example Sort, BinarySearch, etc. However, there are a couple of methods where a generic overload is missing, specifically Clear, Copy, and Reverse.

This hinders optimizations, since we cannot directly access the elements in the array from C#-- we either have to call GetValue and box it, or call into the runtime to do so. So for example, if the array's length is under a certain threshold in Copy we would want to stick to a normal for-loop instead of calling into native code. However, since those methods are non-generic, that is currently impossible.

The above problem is particularly bad with Reverse: if the elements in the array are non-primitive structs, then every single element in the array will be boxed. Link to source.

In addition, the lack of type safety means that in Copy, which accepts 2 Array parameters, we have to perform extra type-checking to make sure the arrays match before the actual copy.

Proposal

We should add generic overloads of Clear, Copy, and Reverse. Any code that currently calls the non-generic overloads will automatically light-up to use these methods. (The parameters should have the same names as the non-generic overloads, so this will work with callers who use named parameters as well.)

namespace System
{
    public abstract class Array : ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
    {
        public static void Copy<T>(T[] sourceArray, T[] destinationArray, int length);
        public static void Copy<T>(T[] sourceArray, int sourceIndex, T[] destinationArray, int destinationIndex, int length);
    }
}

edit: @justinvp has already submitted a proposal for a generic Reverse which was approved, so I removed that from the proposed API.

edit: Removed generic Clear from this proposal after @terrajobst's comment. That's now being tracked in dotnet/corefx#11839.

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-needs-workAPI needs work before it is approved, it is NOT ready for implementationarea-System.Runtime

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions