Generating Random Numbers C#
When tasked with generating Random numbers, some folks use a static method such as that shown below:
Code Snippet
- static Random rn = new Random();
- static int ReturnNextRandom(int maxIndex)
- {
- return rn.Next(maxIndex);
- }
One of the reasons is that they want to keep the same, common instance of the Random Generator (Random class in C#). While this makes sense, there is no reason to stick to static methods – and be able to not do an instance method. The code below shows a way to use an OO approach – define a RandomGenerator class – which does exactly the same thing as the static method above.
Code Snippet
- interface IRandomGenerator
- {
- int ReturnNextRandom(int maxIndex);
- }
- class RandomGenerator : IRandomGenerator
- {
- private static Random _rnd = new Random();
- private static object _lock = new object();
- public int ReturnNextRandom(int maxIndex)
- {
- return Next(maxIndex);
- }
- private int Next(int maxIndex)
- {
- lock (_lock)
- {
- return _rnd.Next(maxIndex);
- }
- }
- }
Full Source Code
Download Source Code RandomGenerator
Technorati Tags: Random numbers c#,generate random numbers c#
Leave a Reply