Random Number Generation in C#

 

Sometimes we have requirement to generate numbers randomly. In C#, we can generate random numbers easily by using Random class in System namespace. 

The Next method of Random class generates the random numbers as shown below.

 

            Random objRandom = new Random(); 

            int iNum = objRandom.Next(); 

            Console.WriteLine(iNum.ToString()); 

            Console.ReadLine();

The Random class Next method generates positive int value range starts from zero(0) to Int32.MaxValue(value is 2,147,483,647). If Next produces values at random, every value in this range has an equal chance (or probability) of being chosen when Next is called. Note that values returned by Next are actually pseudo-random numbers—a sequence of values produced by a complex mathematical calculation. A seed value is required in this mathematical calculation. When we create our Random object, we use the current time of day as the seed. A particular seed value always produces the same series of random numbers. Programmers commonly use the current time of day as a seed value, since it changes each second and, therefore produces different random-number sequences each time the program executes.

 

You can generate numbers within your required range. That means if you want to generate random numbers between 0 to 10, you can generate by using below code.

 

using System;

namespace CSharpRandomNumbers 

{ 

    class Program 

    { 

        static void Main(string[] args) 

        { 

            Random objRandom = new Random(); 

            int iNum = objRandom.Next(10);

            Console.WriteLine(iNum.ToString()); 

            Console.ReadLine(); 

        } 

    } 

}

As shown above we can generate random numbers by passing value to the Next method. Even you can generate random numbers within specified range not starting from 0 as shown below. 

using System;

namespace CSharpRandomNumbers

{ 

    class Program 

    { 

        static void Main(string[] args) 

        { 

            Random objRandom = new Random(); 

            int iNum = objRandom.Next(51,100);

            Console.WriteLine(iNum.ToString()); 

            Console.ReadLine(); 

        } 

    } 

}

The above code generates the random number between 50 and 100.