Random oddity


Recently I wrote a program to reshuffle data in a csv file. And I ran into a problem with Random in C#.

Let’s look at the following program. One would think that it should print 5 integers, randomly picked between 0 and 8. But no, in almost all cases, the program prints the same integer 5 times.

[sourcecode language=”c#”]
using System;
class Scaffolding
{
static void Main(string[] args)
{
for (int i = 0; i < = 5; ++i) { Random randomNumber = new Random(); Console.WriteLine(randomNumber.Next(9)); } } } [/sourcecode] It turns out the correct way, and more efficient way according to documentation, is to instantiate one static Random class to generate many random numbers over time, instead of repeatedly creating a new Random to generate one random number, like so: [sourcecode language="c#"] using System; class Scaffolding { static Random randomNumber = new Random(); static void Main(string[] args) { for (int i = 0; i <= 5; ++i) { Console.WriteLine(randomNumber.Next(9)); } } } [/sourcecode] MSDN documentation is here.


Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.