Skip to content

EnumerableSelectIterator invokes selector in MoveNext() #99359

Discussion options

You must be logged in to vote

If the selector function throws, or has other side effects, those should be observed by Count(); etc.

e.g.

private static int s_count = 0;

...

var enumerable = data.Select(e => { s_count++; return e; });
enumerable.Count();

foreach (var item in enumerable)
{
    ...
}

Changing the implementation to only invoke the selector when the item is being extracted would change the value of s_count produced by the above code. Furthermore, it would be quite surprising if

A)

private static int Count<T>(IEnumerable<T> data)
{
    IEnumerable<T> enumerable = data.Select(selector);
    int count = 0;
    IEnumerator<T> iterator = enumerable.GetEnumerator();

    while (iterator.MoveNext()) { count++; }

Replies: 2 comments 5 replies

Comment options

You must be logged in to vote
1 reply
@ActivistInvestor
Comment options

Comment options

You must be logged in to vote
4 replies
@ActivistInvestor
Comment options

@stephentoub
Comment options

@ActivistInvestor
Comment options

@stephentoub
Comment options

Answer selected by ActivistInvestor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Ideas
Labels
None yet
3 participants