[Mono-dev] Issues with System.Random

Adrian Willenbücher AWillenbuecher at gmx.de
Wed Mar 17 11:33:36 EDT 2010


Kornél Pál wrote:
> You can use the OnDeserializedAttribute and NonSerializedAttribute 
> attributes.

Unfortunately that doesn't allow me to incorporate the serialized state. Instead, I think I found a better solution by 
explicitly (de)serializing the object. It first tries to deserialize the object from the new version, and if that fails, 
from the old one. If anything doesn't work, the RNG will still be seeded and functional.

	public class Random : ISerializable
	{
		// ...

		protected Random (SerializationInfo info, StreamingContext context) : this(0)
		{
			if (info == null)
				throw new ArgumentNullException ("info");

			try {
				var new_state = (uint[]) info.GetValue ("state", typeof(uint[]));
				new_state.CopyTo (state, 0);
				return;
			} catch (SerializationException) {
				// Let's try deserializing from the old version (below).
			} catch (Exception) {
				// Something was wrong, but we don't care; no need to crash the program.
				return;
			}

			try {
				var old_state = (int[]) info.GetValue ("SeedArray", typeof(int[]));
				for (var i = 0; i < 5; ++i)
					state [i] ^= (uint) old_state [i + 1];
				return;
			} catch (Exception) {
				// It still didn't work? No worries, the RNG will function correctly nevertheless.
			}
		}

		public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
		{
			if (info == null)
				throw new ArgumentNullException ("info");
			info.AddValue ("state", state);
		}

		// ...
	}


More information about the Mono-devel-list mailing list