I'm trying to deep clone an object which contains a System.Random variable. My application must be deterministic and so I need to capture the the random object state. My project is based on .Net Core 2.0.
I'm using some deep clone code from here (How do you do a deep copy of an object in .NET (C# specifically)?) which uses serialization.
The documentation for System.Random is mixed:
Serializable
https://msdn.microsoft.com/en-us/library/system.random(v=vs.110).aspx
http://referencesource.microsoft.com/#mscorlib/system/random.cs,bb77e610694e64ca (source code)
Not Serializable
https://learn.microsoft.com/en-us/dotnet/api/system.random?view=netframework-4.7.1
https://learn.microsoft.com/en-us/dotnet/api/system.random?view=netcore-2.0
and I get the following error.
System.Runtime.Serialization.SerializationException HResult=0x8013150C Message=Type 'System.Random' in Assembly 'System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' is not marked as serializable. Source=System.Runtime.Serialization.Formatters
Can System.Random it be cloned in the way I want?
I created a small program to illustrate.
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace RandomTest
{
class Program
{
static void Main(string[] args)
{
Container C = new Container();
Container CopyC = DeepClone(C);
}
public static T DeepClone<T>(T obj)
{
using(var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj); //<-- error here
ms.Position = 0;
return (T)formatter.Deserialize(ms);
}
}
}
[Serializable]
public class Container
{
public ObjectType AnObject;
public Container()
{
AnObject = new ObjectType();
}
}
[Serializable]
public class ObjectType
{
//[NonSerialized] // Uncommenting here removes the error
internal System.Random R;
}
}
I probably don't need the Container object, but this structure more closely resembles my application.
Making R [NonSerialized] removes the error but I don't get my Random object back after deserialization. I tried re-creating the random object, but it starts a new random sequence and so breaks the deterministic requirement.