user3488765 user3488765 - 23 days ago 6
C# Question

Does calling .toArray() on an ICollection that is an Array return the reference or a copy?

I am working on a few extension methods where I need to transform the input collection into an Array.
I want to save memory so I only want to create a copy of the input if it is absolutely necessary.

Do I have to do:

public static ICollection<TSource> ExtMethod<TSource>(this ICollection<TSource> source, Func<TSource, int> predicate)
{
TSource[] converted;
if (source is TSource[])
{
converted = source as TSource[];
}
else {
converted = source.ToArray();
}

}


Or does toArray do the check under the hood and I have exactly the same effect if I do:

public static ICollection<TSource> ExtMethod<TSource>(this ICollection<TSource> source, Func<TSource, int> predicate)
{
TSource[] converted = source.ToArray();
}

Answer

ToArray always creates a copy. Your extension method does not behave the same way.

Note that there are subtleties here around types as well. Consider this code:

string[] x = { "a", "b" };
object[] y = x.ExtMethod<object>();
object[] z = x.ToArray<object>();

Now the execution-time type of y is string[] because it's returned the original array - but the execution-time type of z is object[] because it's created a new array with the type argument specified.