Random Method in C#

Rolling a six sided die problem

In this problem the application simulate 20 rolls of a six sided die and display the value of each roll. So, in this problem we use

random class : the object of class random can produce random byte,int,double values

Scaling factor:

  1. int randomValue = random.Next(6);  

In the above statement we use randomvalue of type integer random is the object of class "Random;", Next is the method of class random

The above statement returns value 0,1,2,3,4,5. The Argument is called Scaling factor- Represent the no. of that Next should produce (in this case 0,1,2,3,4 and 5)

This manipulation is called scaling the range of value produce by Random method Next.

Shifting factor

Suppose we want to simulate six die and that has the numbers 1-6 on its faces, not 0-5. Scaling the range of value is not enough. So we shift the range of numbers we produced. We could do this by adding shifting value – in this case 1- to the result of method next, as in

  1. int randomValue =1+ random.Next(6);  
  2.   
  3. OR  
  4.   
  5. int randomValue = random.Next(1,6);  

Here we have two example of class random.