0

I saw the post on ways to handle an infinite IEnumerable, but I didn't see a good answer for testing if an enumerable is infinite.

My end goal is to write a function for all collection types in .NET, but to safely traverse the whole collection without the risk of long wait times due to some infinite collection.

OPT1: I thought I might be able tell if an enumerable is infinite and throw an exception. However, I figure this would be the approach for .NET aggregate LINQ expressions (e.g. Max, Count) if it were possible.

  • EDIT: As suspected, another question was suggested that directly declares this option impossible

OPT2: Is there some other abstraction that supports most all enumerable types, but disallows infinite elements? ICollection looks promising, supports lists and arrays, but not Queues or many custom IEnumerables.

I'm also having a hard time determining if ICollection can be infinite or not.

Suggestions?

farlee2121
  • 2,959
  • 4
  • 29
  • 41
  • try out IReadOnlyCollection, which is basically the same as IEnumerable + int Count property – jalepi Mar 30 '22 at 21:02
  • 2
    How could you possibly tell if an arbitrary `IEnumerable` is infinite? That would require knowledge of the implementation. `ICollection` has a `Count` property: that would imply that the number of elements is known. Once cast to an `IEnumerable`, that knowledge goes away and isn't available to whoever receives it (without peeking at the implementation). – Nicholas Carey Mar 30 '22 at 21:30
  • @user1344783 I don't think most collections support IReadOnlyCollection. I'd end up pushing the infinity risk (and conversion) on the caller – farlee2121 Mar 30 '22 at 21:51
  • 2
    Does this answer your question? [Is there a way to determine whether IEnumerable is a sequence generator or true collection?](https://stackoverflow.com/questions/7796443/is-there-a-way-to-determine-whether-ienumerablet-is-a-sequence-generator-or-tr) – gunr2171 Mar 30 '22 at 21:53
  • 1
    @farlee2121, most concrete implementations in C# support IReadOnlyCollection, List, Collection, HashSet, you can name it, it probably supports. Don't use IList because that is the worse interface and it should not exist. – jalepi Mar 30 '22 at 22:09
  • @user1344783 Hmm, a good point. I think that may be as close as I can get – farlee2121 Mar 30 '22 at 22:31
  • @gunr2171 That link is a great call out that I hadn't found. It does provide a more definitive answer to OPT1, but there is still the OPT2 with some alternative abstraction. I think user1344783's suggestion of `IReadOnlyCollection` is probably about as good as I can hope for. It just seems like such a fundamental building block to have such a dangerous information hiding violation. – farlee2121 Mar 30 '22 at 22:35

0 Answers0