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.
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.
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();
}
}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.
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).
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.