Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing IEnumerator<T> created using yield return

Is there a way to serialize (using BinaryFormatter) the IEnumerator<T> that gets created when I use yield returns? The autogenerated class isn't marked Serializable.

like image 257
svick Avatar asked Jul 01 '10 22:07

svick


People also ask

How do you use yield return?

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.

Does yield return a list?

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.

What is yield return C#?

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.

Do methods get serialized?

Methods aren't serialized.


1 Answers

Which class are you using to implement IEnumerable<T>? List<T> should serialize OK.

Try calling ToList() on your collection before serializing it.

like image 192
Robert Harvey Avatar answered Oct 05 '22 03:10

Robert Harvey