Does Array.ToArray<>() return the original array if it is the same type?

前端 未结 2 1253
执笔经年
执笔经年 2020-12-16 08:53

I deal with a framework on a daily basis where we sometimes provide methods that accept IEnumerable as a parameter in order to show user

相关标签:
2条回答
  • 2020-12-16 09:40

    No, you will always get a new copy of the array, though the objects in it aren't copies, they are the same references as in the original array.

    It would be very inconsistent for changes to the returned array to sometimes affect the source and sometimes not. ToList works the same way for the same reason.


    You can check source code (as of 2015) if you need to review details: Enumerable.ToArray which in turn creates copy of elements (optimized for ICollection and hence Array[], but still making copy) with internal Buffer class.

    0 讨论(0)
  • 2020-12-16 09:52

    You will get a new copy of the array if there is one or more element in it. For empty arrays, you might get the same array back, at least in .NET 5:

    Console.WriteLine(Object.ReferenceEquals(Array.Empty<string>(), Array.Empty<string>().ToArray()));
    

    This returns true.

    0 讨论(0)
提交回复
热议问题