ImmutableArray <> behaves differently than Array <> for nested selection with index

I come across what seems like a very strange error in ImmutableArray<> (with BCL Immutable collections v1.0.12.0, runtime.NET 4.5):

I have the following two identical structures in exactly the same source file in the same namespace:

 public struct WeightedComponent { public readonly IComponent Component; public readonly decimal Weight; public WeightedComponent(IComponent component, decimal weight) { this.Component = component; this.Weight = weight; } } public struct WeightedComponent2 { public readonly IComponent Component; public readonly decimal Weight; public WeightedComponent2(IComponent component, decimal weight) { this.Component = component; this.Weight = weight; } } 

The following throws an exception:

 var elements1 = new[] { 1, 2, 3 }.Select(wc => new WeightedComponent(null, 0)).ToImmutableArray(); var foo = elements1.Select((e1, i1) => elements1.Select((e2, i2) => 0).ToArray()).ToArray(); if (foo.Length != 3) throw new Exception("Error: " + foo.Length); //Error: 1 var elements2 = new[] { 1, 2, 3 }.Select(wc => new WeightedComponent2(null, 0)).ToImmutableArray(); var foo2 = elements2.Select((e1, i1) => elements2.Select((e2, i2) => 0).ToArray()).ToArray(); if (foo2.Length != 3) throw new Exception("Error: " + foo.Length); 

If I design elements1 in ToArray() in the first line instead of ToImmutableArray() , everything works fine.

The only difference between the two structures is that WeightedComponent widely used by code before, and WeightedComponent2 never used before (therefore, it may not be obvious to reproduce the error).

Iterating over elements1 twice in the same expression seems to be related to the problem, as if I were deleting it, Select works fine, but there is no such problem with elements2 . This seems to be due to the way the code behind ImmutableArray<> considers both structures (maybe there is a caching mechanism?)

Do you have any ideas what might be causing this?

+4
source share
1 answer

This is due to an error in the ImmutableArray<T> enumerator caused by the first enumeration of an empty collection instance. A future version of the NuGet package will fix the problem. In the meantime, I highly recommend avoiding the use of ImmutableArray<T> .

+3
source

Source: https://habr.com/ru/post/1501448/


All Articles