Dot Net Perls

Random Number Generator Use - C#

by Sam Allen

Problem

Generate random numbers efficiently. Although your algorithm cannot be truly random, it must appear so for any human being observing it. You may want to use this in a simple game or in rotating content. Examine random numbers in object-oriented programs.

Solution: C#

I will spare you the theoretical aspect of random numbers. Instead, let's look at the C# random number generator. Microsoft provides some useful resources, and it says the following things about these methods.

How can I code it?

You can put the Random object in a new class, and then just use that class when you want to make a new random number. The examples at Microsoft use parameters, but this is more object-oriented and easy.

using System;

class RandomNum
{
    /// <summary>
    /// The random object. It is automatically initialized with a time
    /// seed. If you only create one object at a time, this is sufficient.
    /// </summary>
    Random _random = new Random();

    /// <summary>
    /// Wrapper method to return the next random number in our
    /// sequence. It is more efficient and more 'random' to
    /// store only one Random object and reuse it.
    /// </summary>
    public int GetRandom()
    {
        return _random.Next();
    }
}

Why do I need to use the class?

You don't always. You can store the Random object locally in a method and directly use it. The example shows how you can use it in the internal part of a class. If you have a class that needs to return a random set of objects, it should store a Random object itself.

Classes should store Random

In object-oriented programming, classes are like "machines", and they should store and manage the Random number generator internally. In the RandomNum example, think of a machine that needs a random number for its output (such as in a simulation).

Conclusion

Use the series of numbers returned by Random.Next() for a pseudo-random number generator. Reuse the same Random generator over the course of your program for best randomness. Store a Random object locally in classes as a member for best performance and good design.

Dot Net Perls
About
Sitemap
Source code
RSS
Integers
Use int.Parse for Integer Conversion
Random Number Generator Use
Numeric Types and Casts
int Max and Min Constants
Math.Max and Min for Bounds-Checking
Recent
Pi
NGEN Installer Class
List Element Equality
DateTime Tips and Tricks
Remove HTML Tags From String
© 2008 Sam Allen. All rights reserved.