[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

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

[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.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.