StackOverflowException on nested query, small item count

Viewed 170

I have found some threads with similar titles, but none seem to have a fitting answer. One mentioned a bug in .NET versions prior to 4.0 - I use 4.0, so this should not be it.

Consider the example: I am attempting to create a collection of instances of class Part, which do not belong to any instance of class PartGroup.

Func<Part,bool> hasGroup = P => partColl.Groups.Any( G => G.Parts.Contains(P) );
var groupless = partColl.Parts.Where( P => ! hasGroup(P) );

partColl is an instance of a class implementing the properties Groups and Parts, each IEnumerable<T> where T is PartGroup or Part respectively, internally implemented as List<T>. partColl.Parts contains all parts in existence. class Group has property IEnumerable<Part> Parts, listing references to parts belonging to the group.

In my current program, there are 27 parts and 5 groups with no overlap in elements. Nothing that should trouble the stack, despite quadratic complexity, if something wasn't foul.
When I run this, it will crash with said exception on hasGroup.

What am I missing?


EDIT: A little detail slipped my abstraction presented here: IEnumerable PartGroup.Parts was, unlike the two properties of PartCollection, not backed by a List, it was an auto-property with private set, initialized in the c'tor with a passed-in IEenumerable. The instance behind this IEnumerable is also a list, and an own one for each group, so I'm not sure yet what is going on exactly.

BUT, the exception is gone by: also backing that property with a variable of type List and in the constructor, assigning to it: _list = parts.ToList(), where parts is IEnumerable<Parts>, passed as a param to the ctor. I did ToList just to make sure it will really be a list, not some half baked query, but it should, since at the place where I am building the groups, one new List for each group is allocated before passing it in...

The remaining question is still interesting: What was going on, why did the auto-property 'cause' the exception? I'll post more details on request, but gotta go for a while now.

1 Answers
Related