I would like to be able to get the actual state or seed or whatever of System.Random so I can close an app and when the user restarts it, it just “reseeds” it with the stored one and continues like it was never closed.
Is it possible?
Using Jon’s idea I came up with this to test it;
static void Main(string[] args)
{
var obj = new Random();
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("c:\\test.txt", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();
for (var i = 0; i < 10; i++)
Console.WriteLine(obj.Next().ToString());
Console.WriteLine();
formatter = new BinaryFormatter();
stream = new FileStream("c:\\test.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
obj = (Random)formatter.Deserialize(stream);
stream.Close();
for (var i = 0; i < 10; i++)
Console.WriteLine(obj.Next().ToString());
Console.Read();
}
It’s serializable, so you may find you can just use
BinaryFormatterand save the byte array…Sample code:
Results on a sample run are promising:
Admittedly I’m not keen on the built-in serialization, but if this is for a reasonably quick and dirty hack, it should be okay…