ICollection types don't work correctly with array access operator [] (Hashtable.Values) - by johndog

Status : 

 


2
0
Sign in
to vote
ID 770389 Comments
Status Active Workarounds
Type Bug Repros 1
Opened 11/7/2012 12:07:09 PM
Access Restriction Public

Description

Use of the array operator on an ICollection does not produce any errors, but the results are non-sensical.

> $h  = @{"a"="1";"b"="2";"c"="3"}
> $h.Values.Count
3
> $h.Values[0]
3
1
2

# wat?

> $h.Values[1]


# wat?

> $h.Values[0]
3
1
2

> $h.Values[0].Count
3

> $h.Values[0][0].Count
3

> $h.Values[0][0][0].Count
3

So it appears that $h.Values and $h.Values[0] return exactly the same thing.  Also,  $h.Values[1 through infinite ] returns $null.

Sign in to post a comment.
Posted by johndog on 11/14/2012 at 9:00 AM
I noticed this problem when I tried to loop over $h.Values with a for loop; it's completely broken if you try.

This:

for ($i = 0; $i -lt $h.Values.Count; $i++) {$h.Values[$i]}

Returns the whole collection when $i is zero, then returns null on every other iteration.
Posted by Roman Kuzmin on 11/8/2012 at 6:04 AM
What you see is more likely the new v3 feature: everything that is not a list (IList?) has a pseudo property Count (0 for null, 1 for a scalar) and can be indexed as [0] getting the same scalar. An instance of ICollection (Hashtable.Values) does not implement IList, as we see.

This new v3 feature is kind of dangerous. When an application exposes ICollection items via API and its implementation changes so that these ICollection start to implement IList or stop to implement IList then scripts using `Count` and `[0]` on these items will be broken, more likely.

+1, although it looks like "by design". But this issue should be better addressed somehow.