Example: Mersenne Twister Random Number Generation

In this example, four simulation streams are generated. The first series is generated with the seed used for initialization. The second series is generated using an array for initialization. The third series is obtained by resetting the generator back to the state it had at the beginning of the second stream. Therefore, the second and third streams are identical. The fourth stream is obtained by resetting the generator back to its original, uninitialized state, and having it reinitialize using the seed. The first and fourth streams are therefore the same.
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Imsl.Stat;

public class MersenneTwisterEx1
{
   /// <summary>
   /// The main entry point for the application.
   /// </summary>


   static void Main(string[] args)
   {
      int nr = 4;
      double[] r = new double[nr];
      int s = 123457;

      /* Initialize MersenneTwister with a seed */
      MersenneTwister mt1 = new MersenneTwister(s);
      MersenneTwister mt2 = (MersenneTwister) mt1.Clone();

      /* Save the state of MersenneTwister */
      Stream stm = new FileStream("mt", FileMode.Create);
      IFormatter fmt = new BinaryFormatter();
      fmt.Serialize(stm,mt1);
      stm.Flush();
      stm.Close();

      Imsl.Stat.Random rndm = new Imsl.Stat.Random(mt1);
              
      /* Get the next five random numbers */
      for (int k=0; k < nr; k++) 
      {
         r[k] = rndm.NextDouble();
      }

      Console.WriteLine("              First Stream Output");
      Console.WriteLine(r[0]+"     "+r[1]+"     "+r[2]+"     "+r[3]);

      /* Check the cloned copy against the original */
      Imsl.Stat.Random rndm2 = new Imsl.Stat.Random(mt2);
      for (int k=0; k < nr; k++) 
      {
         r[k] = rndm2.NextDouble();
      }

      Console.WriteLine("\n              Clone Stream Output");
      Console.WriteLine(r[0]+"     "+r[1]+"     "+r[2]+"     "+r[3]);
              
      /* Check the serialized copy against the original */
      System.IO.Stream stm2 = new FileStream("mt", FileMode.Open);
      IFormatter fmt2 = new BinaryFormatter();
      mt2 = (MersenneTwister)fmt2.Deserialize(stm2);
      stm2.Close();

      Imsl.Stat.Random rndm3 = new Imsl.Stat.Random(mt2);
      for (int k=0; k < nr; k++) 
      {
         r[k] = rndm3.NextDouble();
      }
      Console.WriteLine("\n              Serialized Stream Output");
      Console.WriteLine(r[0]+"     "+r[1]+"     "+r[2]+"     "+r[3]);
   }
}

Output

              First Stream Output
0.434745062375441     0.352208853699267     0.0138511140830815     0.20914130914025

              Clone Stream Output
0.434745062375441     0.352208853699267     0.0138511140830815     0.20914130914025

              Serialized Stream Output
0.434745062375441     0.352208853699267     0.0138511140830815     0.20914130914025

Link to source.