How to generate a random number in .NET

In other programming languages and dialects, you would use a command such as RND() to Generate a Random Number but with .NET, you would need to use an object called surprisingly Random. You would instantiate an instance of the class first before you use. You do not need to reference any libraries apart from probably System but as every solution does, you don't need to remember, its automatic. If you need to use the code in VB.NET, you just knock off the semi-colon at the end and change how you declare the variables.

    Random oRand = new Random();

Then you'd use the Next method of the object to actually generate a number as below.

    decimal dValue = oRand.Next();

The number that would be generated is a value between 1 and int.MaxValue which is 2147483647 which if you need to generate numbers for a UK lottery ticket for example which the number goes from 1 to 59, it'll probably be a long time before it generates a number which is in range. To get round the problem, you can use the optional parameters of the Next command to generate only a number between 1 and 50.

    decimal dValue = oRand.Next(1,59);

If you only specify the first number then the range will go from 1 to int.MaxValue so you will need to specify the last parameter to generate a lottery number. If you need to generate a number that is a decimal, well double, you can use the NextDouble() function. The function will only generate a large decimal places number between 0 and 1. To generate a random double number between 0 and 10, you will have to combine the values of Next and NextDouble.

    Random oRand = new Random();
    double dValue = oRand.NextDouble();
    double dInt = oRand.Next(0,10);

    dInt += dValue;

    Console.WriteLine(dInt.ToString());

If the number of decimal places should not exceed 2 dp, you can use the Round function which was discussed in the previous article, the link at the bottom of the page.

It is possible to generate a sequence of number between 0 and 255 with one command, rather than calling the function individually. You need to create a byte array and fill it with the number of random numbers you wish to generate and then call NextBytes as below.

    byte[] Message = {0,0,0,0,0,0 };
    oRand.NextBytes(Message);
    foreach(byte B in Message)
        Console.WriteLine(B.ToString());

The last method to be discussed is GetHashCode() which will return an integer that is the value that was used to generate the random number.

Tags - .NET

Last Modified : June 2023


About... / Contact.. / Cookie...