Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Sharing the Random Generator


The solution which I provide is based on the Singleton design pattern, which we will discuss later in the teaching material. I make my own Random class, which cannot be instantiated because it is a singleton. Thus, you should use Random.Instance() instead of new Random(...).

using System;

public class Random {

  // Singleton pattern:
  // Keeps track of unique instance of this class
  private static Random uniqueInstance = null;

  // Holds the instance of System.Random
  private System.Random systemRandom;

  // Singleton pattern: Private constructor.
  private Random(){
    systemRandom = new System.Random(unchecked((int)DateTime.Now.Ticks));
  }

  public static Random Instance(){
    if (uniqueInstance == null)
      uniqueInstance = new Random();
    return uniqueInstance;
  }

  public int Next(int lower, int upper){
    // delegate to systemRandom
    return systemRandom.Next(lower,upper);
  }

}

Notice that uniqueInstance is a class class variable (static variable) in class Random. Notice also that the method called Instance is a class method (static method).