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 MersenneTwister64Ex1
{
   /// <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 MersenneTwister64 with a seed */
      MersenneTwister64 mt1 = new MersenneTwister64(s);
      MersenneTwister64 mt2 = (MersenneTwister64) mt1.Clone();

      /* Save the state of MersenneTwister64 */
      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 = (MersenneTwister64)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.579916541818503     0.940114746325065     0.710159376724905     0.163995293979278

              Clone Stream Output
0.579916541818503     0.940114746325065     0.710159376724905     0.163995293979278

              Serialized Stream Output
0.579916541818503     0.940114746325065     0.710159376724905     0.163995293979278

Link to source.