Is it possible to serialize a method containing yield statements (or a class that contains such a method) such that when you rehydrate the class, the internal state of the generated iterator is retained?
Is it possible to serialize a method containing yield statements (or a class that
Share
Yes, you can do this. With caveats.
An example of serializing a method with a
yield, deserializing and continuing can be found here: http://www.agilekiwi.com/dotnet/CountingDemo.cs (Web Archive Link).In general, trying to serialize without doing some extra work will fail. This is bcause the compiler generated classes are not marked with the
Serializableattribute. However, you can work around this.I would note the reason that they aren’t marked with serializable is because they are an implementation detail and subject to breaking changes in future versions, so you may not be able to deserialize it in a newer version.
Related to a question I asked on how to serialize anonymous delegates, which should work for this case as well.
Here’s the source code of the “hack”: