# Make extension methods to generate random double values in C#

This example adds extension methods to the Random class to generate double values within a specified range.

The Random class provides methods for generating pseudo-random numbers. The Next method has three overloaded versions that produce a non-negative integer, an integer between 0 and some upper bound, and an integer between lower and upper bounds.

Strangely the Random class’s NextDouble method has only one version that returns a value between 0.0 and 1.0. This example adds the two other obvious versions to produce double values between 0.0 and an upper bound and between two bounds.

The following code shows the RandomExtensions class that implements the extension methods.

```public static class RandomExtensions
{
// Return a random value between 0 inclusive and max exclusive.
public static double NextDouble(this Random rand, double max)
{
return rand.NextDouble() * max;
}

// Return a random value between min inclusive and max exclusive.
public static double NextDouble(this Random rand,
double min, double max)
{
return min + (rand.NextDouble() * (max - min));
}
}```

There are no big tricks here. The first method uses the original NextDouble method to get a value between 0.0 and 1.0. It multiplies that by the upper bound to get a value between 0.0 and the upper bound and returns the result.

The second method also uses the original NextDouble method to get a value between 0.0 and 1.0. It multiplies that by (max - min) and adds that to the lower bound. Because the random number generator gives a value between 0.0 and 1.0, the result is between:

`    min + 0.0 * (max - min) = min`

and

`    min + 1.0 * (max - min) = min + (max - min) = max`

The value is between min and max as desired so the method returns it.

This entry was posted in extension methods, mathematics and tagged , , , , , , , , , , . Bookmark the permalink.

### 1 Response to Make extension methods to generate random double values in C#

This site uses Akismet to reduce spam. Learn how your comment data is processed.