Generating Random Number In C#

In this article, learn how to generate random numbers in C# using the Random class.

Before we dive into the details of the System.Random class, we should talk about randomness in discrete mathematics. The two most common scenarios for generating random numbers are generating integers uniformly between 1 and n and generating real numbers uniformly between 0 and 1. Most random-number-generation algorithms are not influenced by the outside universe; they are inherently pseudorandom: predictable and following a pattern (ideally not an obvious one). You should keep in mind the following two statements on pseudorandomness made by respected computer science masters: 
  • "Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin." - John Von Neumann (1951)
  • "Random number generators should not be chosen at random." - Donald Knuth (1986)
 
Let's go back to our main focus now. We use the System.Random class to produce a random number. System.Random can return both decimal and integer random numbers. In addition, System.Random by design can seed its random number generator with a random value derived from the computer system clock. 
  1. System.Random rnd = new System.Random();  
You can initialize the seed with any Int32 value on demand at times when the system clock is not fast enough to refresh or when you need to synchronize your random number generators across a network. This is also the common use of a seed to synchronize two random number generators. 
  1. System.Random rnd = new System.Random((int)DateTime.Now.Ticks);  
The Random class includes a series of methods allowing you to retrieve the next number produced by the random number generator. The NextDouble method returns a double random number between 0.0 and 1.0. The Next method returns an integer random number between two integer values. The NextBytes method fills the elements of a specified array of bytes with random numbers. The NextDouble, Next, and NextBytes methods are instance methods; therefore, you must instantiate a System.Random object before using them.
 
The Next() method has three overloads:
  1. // a positive random number  
  2. public virtual int Next();  
  3. // a positive random number less than the specified maximum  
  4. public virtual int Next(int);  
  5. // a random number within a specified range  
  6. public virtual int Next(intint );  
  7. You can use the Next method overloads as shown in Listing 21.37.  
  8. Listing 21.37: Using the Next Property  
  9. // any valid integer random number  
  10. Int32 dbl1 = rnd.Next();  
  11. // an integer between 0< and UpperBound where UpperBound + 1 >= 0  
  12. Int32 dbl1 = rnd.Next(UpperBound + 1);  
  13. // an integer between LowerBound< and UpperBound where UpperBound + 1 >= 0  
  14. // and LowerBound <= UpperBound + 1  
  15. Int32 dbl1 = rnd.Next(LowerBound, UpperBound + 1);  
Using the NextDouble method of the Random class produces the next pseudorandom double value that is greater than 0.0 and less than 1.0. 
  1. Double dbl1 = rnd.NextDouble();  
The NextBytes method of the Random class produces an array of random bytes with values ranging from 0 to MaxValue (MaxValue = 255). 
  1. Byte[] mybytes = new Byte[5];   
  2. // mybytes is filled with 5 bytes of random data  
  3. rnd.NextBytes(mybytes);  
The program in Listing 21.38 generates unique integer random numbers in the ranges that you send to the application and then displays them on the console
 
Listing 21.38: Generating Unique Random Numbers with Next(Int32, Int32) 
  1. using System;  
  2. class testrandom  
  3. {  
  4. public static void Main(string[] args)  
  5. {  
  6. int intno;  
  7. if (args.Length == 0)  
  8. {  
  9. Console.WriteLine("Please enter a parameter eg. unique 5");  
  10. return;  
  11. }  
  12. else  
  13. {  
  14. intno = Int32.Parse(args[0]);  
  15. if (intno < 1)  
  16. {  
  17. // Check to see if user has entered value >= 1  
  18. // because my LowerBound is hardcoded to 1  
  19. Console.WriteLine("Enter value greater than or equal to 1");  
  20. return;  
  21. }  
  22. }  
  23. unique_random generateit = new unique_random();  
  24. generateit.create_random(intno);  
  25. }  
  26. }  
  27. class unique_random  
  28. {  
  29. public void create_random(int passed_intno)  
  30. {  
  31. int LowerBound = 1;  
  32. int UpperBound = passed_intno;  
  33. bool firsttime = true;  
  34. int starti = 0;  
  35. int[] vararray;  
  36. vararray = new int[UpperBound];  
  37. // Random Class used here  
  38. Random randomGenerator = new Random(DateTime.Now.Millisecond);  
  39. do  
  40. {  
  41. int nogenerated = randomGenerator.Next(LowerBound, UpperBound + 1);  
  42. // Note: randomGenerator.Next generates no. to UpperBound - 1 hence +1  
  43. // i got stuck at this pt & had to use the debugger.  
  44. if (firsttime) // if (firsttime == true)  
  45. {  
  46. vararray[starti] = nogenerated;  
  47. // we simply store the nogenerated in vararray  
  48. firsttime = false;  
  49. starti++;  
  50. }  
  51. else // if (firsttime == false)  
  52. {  
  53. bool duplicate_flag = CheckDuplicate(nogenerated, starti, vararray);  
  54. // call to check in array  
  55. if (!duplicate_flag) // duplicate_flag == false  
  56. {  
  57. vararray[starti] = nogenerated;  
  58. starti++;  
  59. }  
  60. }  
  61. while (starti < UpperBound);  
  62. PrintArray(vararray); // Print the array  
  63. }  
  64. public bool CheckDuplicate(int newrandomNum, int loopcount, int[] function_array)  
  65. {  
  66. bool temp_duplicate = false;  
  67. for (int j = 0; j < loopcount; j++)  
  68. {  
  69. if (function_array[j] == newrandomNum)  
  70. {  
  71. temp_duplicate = true;  
  72. break;  
  73. }  
  74. }  
  75. return temp_duplicate;  
  76. }  
  77. // Print Array  
  78. public static void PrintArray(Array arr)  
  79. {  
  80. Console.Write("{");  
  81. int count = 0;  
  82. int li = arr.Length;  
  83. foreach (object o in arr)  
  84. {  
  85. Console.Write("{0}", o);  
  86. count++;  
  87. //Condition to check whether ',' should be added in printing arrray  
  88. if (count < li)  
  89. Console.Write(", ");  
  90. }  
  91. Console.WriteLine("}");  
  92. }  
  93. }  
 
Conclusion
 
Hope this article have helped you in understanding generating random numbers using the System.Random class in C#.