Search code examples
c#randomnumbersgenerator

How does C#'s random number generator work?


I was just wondering how the random number generator in C# works. I was also curious how I could make a program that generates random WHOLE INTEGER numbers from 1-100.


Solution

  • I was just wondering how the random number generator in C# works.

    That's implementation-specific, but the wikipedia entry for pseudo-random number generators should give you some ideas.

    I was also curious how I could make a program that generates random WHOLE INTEGER numbers from 1-100.

    You can use Random.Next(int, int):

    Random rng = new Random();
    for (int i = 0; i < 10; i++)
    {
        Console.WriteLine(rng.Next(1, 101));
    }
    

    Note that the upper bound is exclusive - which is why I've used 101 here.

    You should also be aware of some of the "gotchas" associated with Random - in particular, you should not create a new instance every time you want to generate a random number, as otherwise if you generate lots of random numbers in a short space of time, you'll see a lot of repeats. See my article on this topic for more details.