SCA1012: By-value Parameter of an Iterator
Do not give an iterator that returns a sequence a by-value parameter of a non-copyable type.
Example
IEnumerable<int> Read(LockGuard guard) { /* ... */ yield return 1; } // SCA1012: every enumeration gets a copy of 'guard'
IEnumerable<int> Read(Session session) { /* ... */ yield return 1; } // OK: an object that holds the guard
How to Fix
- Create the value inside the iterator.
- Pass an object that holds it, as
Sessiondoes above.
Details
A method or a local function with yield that returns a sequence has a by-value parameter of a non-copyable type. The compiler keeps the arguments of an iterator in the object that it returns and copies them into every enumerator. So what the iterator does with the parameter runs on a copy, once for each enumeration.
- The by-value receiver of an extension block is such a parameter of every iterator in the block, and gets a warning at the iterator.
- An iterator that returns an enumerator (IEnumerator<T>, IAsyncEnumerator<T>) keeps its arguments once, and gets no warning.
- A by-value parameter of an
asyncmethod gets no warning either: the compiler keeps it in the state machine once, and the method works on that one place.
See Also
These articles explain the rule behind this warning:
- Fields, Interfaces and Async Members - the declarations that copy a value by themselves.
Didn't add this analyzer yourself? See Why Am I Seeing This?