Random number always the same – C#
filed in C# on Jan.31, 2010
A typical mistake when creating random number in C# is to forget the static definition.
To make the C# random class work appropriately, make sure that the declaration of your random is static as follow.
using System;
class Program {
static void Main()
{
// Call method that uses class-level Random
TestRandom();
/*
Call same method
The random number sequence still be random
*/
TestRandom();
}
private static rNum = new Random();
static void TestRandom()
{
/*
Use class-level Random so that when this
method is called many times, it still has
good Randoms.
*/
int n = rNum.Next();
Console.WriteLine(n);
}
}
Leave a Reply