2
2
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
3
4
4
using System . Collections . Generic ;
5
+ using System . Diagnostics ;
5
6
using System . Diagnostics . Contracts ;
6
7
using System . Linq ;
7
8
using Validation ;
@@ -107,11 +108,12 @@ public static ImmutableArray<T> CreateRange<T>(IEnumerable<T> items)
107
108
{
108
109
immutableArray . ThrowInvalidOperationIfNotInitialized ( ) ;
109
110
110
- var existingImmutableArray = immutableArray . Array as T [ ] ;
111
- if ( existingImmutableArray != null || immutableArray . Array == null )
112
- {
113
- return new ImmutableArray < T > ( existingImmutableArray ) ;
114
- }
111
+ // immutableArray.Array must not be null at this point, and we know it's an
112
+ // ImmutableArray<T> or ImmutableArray<SomethingDerivedFromT> as they are
113
+ // the only types that could be both IEnumerable<T> and IImmutableArray.
114
+ // As such, we know that items is either an ImmutableArray<T> or
115
+ // ImmutableArray<TypeDerivedFromT>, and we can cast the array to T[].
116
+ return new ImmutableArray < T > ( ( T [ ] ) immutableArray . Array ) ;
115
117
}
116
118
117
119
// We don't recognize the source as an array that is safe to use.
@@ -534,14 +536,10 @@ public static int BinarySearch<T>(this ImmutableArray<T> array, int index, int l
534
536
/// <summary>
535
537
/// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct.
536
538
/// </summary>
537
- /// <param name="items">The array to use or copy from. May be null for "default" arrays .</param>
539
+ /// <param name="items">The array from which to copy .</param>
538
540
internal static ImmutableArray < T > CreateDefensiveCopy < T > ( T [ ] items )
539
541
{
540
- // Some folks lazily initialize fields containing these structs, so retaining a null vs. empty array status is useful.
541
- if ( items == null )
542
- {
543
- return default ( ImmutableArray < T > ) ;
544
- }
542
+ Debug . Assert ( items != null ) ;
545
543
546
544
if ( items . Length == 0 )
547
545
{
@@ -550,7 +548,7 @@ internal static ImmutableArray<T> CreateDefensiveCopy<T>(T[] items)
550
548
551
549
// defensive copy
552
550
var tmp = new T [ items . Length ] ;
553
- Array . Copy ( items , tmp , items . Length ) ;
551
+ Array . Copy ( items , 0 , tmp , 0 , items . Length ) ;
554
552
return new ImmutableArray < T > ( tmp ) ;
555
553
}
556
554
}
0 commit comments