[Mono-dev] Issues with System.Random

Adrian Willenbücher AWillenbuecher at gmx.de
Wed Mar 17 13:31:30 EDT 2010


Robert Jordan wrote:
> Implementing an interface is a breaking change of the API.
> That's why Konél was mentioning OnDeserializedAttribute.

Thanks for the info, I didn't know that (I'm pretty new to C#, Mono and .NET). The only alternative I could come up with 
is this:

	[Serializable]
	[ComVisible (true)]
	public class Random
	{
		private int inext;
		private int inextp;
		private int [] SeedArray;

		private uint [] state = new uint [5];

		public Random () : this(Environment.TickCount)
		{
		}

		public Random (int Seed)
		{
			SeedState (Seed);
		}

		private void SeedState (int seed)
		{
			state = new uint[5];
			state[0] = 123456789 ^ (uint) seed;
			state[1] = 362436069;
			state[2] = 521288629;
			state[3] = 88675123;
			state[4] = 886756453;
		}

		[OnDeserialized()]
		private void PostDeserialization (StreamingContext context)
		{
			if (state == null || state.Length < 5)
				SeedState (0);

			try {
				if (SeedArray != null) {
					for (var i = 0; i < 5; ++i)
						state[i] ^= (uint) SeedArray[i + 1];
				}
			} finally {
				// We don't need SeedArray anymore
				SeedArray = null;
			}
		}
	// ...
}


It's not very beautiful, but seems to work. I couldn't use [NonSerialized] on the three legacy fields because that 
results in an exception complaining about "inext not in class System.Random" when loading an old serialized object.


More information about the Mono-devel-list mailing list