Produce a random number in a range using C#

C#.NetRandom

C# Problem Overview


How do I go about producing random numbers within a range?

C# Solutions


Solution 1 - C#

You can try

Random r = new Random();
int rInt = r.Next(0, 100); //for ints
int range = 100;
double rDouble = r.NextDouble()* range; //for doubles

Have a look at

Random Class, Random.Next Method (Int32, Int32) and Random.NextDouble Method

Solution 2 - C#

Try below code.

Random rnd = new Random();
int month = rnd.Next(1, 13); // creates a number between 1 and 12
int dice = rnd.Next(1, 7); // creates a number between 1 and 6
int card = rnd.Next(52); // creates a number between 0 and 51

Solution 3 - C#

Something like:

var rnd = new Random(DateTime.Now.Millisecond);
int ticks = rnd.Next(0, 3000);

Solution 4 - C#

Use:

Random r = new Random();
 int x= r.Next(10);//Max range

Solution 5 - C#

For future readers if you want a random number in a range use the following code:

public double GetRandomNumberInRange(double minNumber, double maxNumber)
{
    return new Random().NextDouble() * (maxNumber - minNumber) + minNumber;
}

C# Random double between min and max

Code sample

Solution 6 - C#

Aside from the Random Class, which generates integers and doubles, consider:

Solution 7 - C#

Here is updated version from Darrelk answer. It is implemented using C# extension methods. It does not allocate memory (new Random()) every time this method is called.

public static class RandomExtensionMethods
{
    public static double NextDoubleRange(this System.Random random, double minNumber, double maxNumber)
    {
        return random.NextDouble() * (maxNumber - minNumber) + minNumber;
    }
}

Usage (make sure to import the namespace that contain the RandomExtensionMethods class):

var random = new System.Random();
double rx = random.NextDoubleRange(0.0, 1.0);
double ry = random.NextDoubleRange(0.0f, 1.0f);
double vx = random.NextDoubleRange(-0.005f, 0.005f);
double vy = random.NextDoubleRange(-0.005f, 0.005f);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRoRView Question on Stackoverflow
Solution 1 - C#Adriaan StanderView Answer on Stackoverflow
Solution 2 - C#Vishal KiriView Answer on Stackoverflow
Solution 3 - C#ozczechoView Answer on Stackoverflow
Solution 4 - C#KayView Answer on Stackoverflow
Solution 5 - C#Darrel K.View Answer on Stackoverflow
Solution 6 - C#Ohad SchneiderView Answer on Stackoverflow
Solution 7 - C#Konstantin GindemitView Answer on Stackoverflow