22. Random doubles

The following NextDouble extension method uses the Random class's existing NextDouble method to generate a double value within a range:

public static class RandomExtensions{    // A Random objects shared by all extensions.    private static Random Rand = new Random();    // Return a double between minValue and maxValue.    public static double NextDouble(this Random rand,        double minValue, double maxValue)    {        return minValue + Rand.NextDouble() * (maxValue - minValue);    }}

The RandomExtensions class creates a Random object at the class level. That object is static, so it is available to all extension methods defined in this class.

If you create a new Random object without passing its constructor a seed value, the class uses the system's ...

Get Improving your C# Skills now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.