Is there a way to serialize (using BinaryFormatter
) the IEnumerator<T>
that gets created when I use yield return
s? The autogenerated class isn't marked Serializable
.
To use "yield return", you just need to create a method with a return type that is an IEnumerable (arrays and collections in. Net implements IEnumerable interface) with a loop and use "yield return" to return a value to set in the loop body.
At first sight, we might think that this is a function which returns a list of 5 numbers. However, because of the yield-statement, this is actually something completely different. This method doesn't in fact return a list at all. What it does is it creates a state-machine with a promise to return 5 numbers.
The yield return statement returns one element at a time. The return type of yield keyword is either IEnumerable or IEnumerator . The yield break statement is used to end the iteration. We can consume the iterator method that contains a yield return statement either by using foreach loop or LINQ query.
Methods aren't serialized.
Which class are you using to implement IEnumerable<T>
? List<T>
should serialize OK.
Try calling ToList()
on your collection before serializing it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With