Why do i need to create an instance of Random class, if i want to create a random number between 1 and 100 ....like
Random rand = new Random();
rand.Next(1,1
It is best practice to create a single instance of Random
and use it throughout your program - otherwise the results may not be as random. This behavior is encouraged by not creating a static function.
You shouldn't worry about "creating an instance unnecessarily", the impact is negligible at best - this is the way the framework works.
From MSDN: Random Class (System):
"The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, while its parameterized constructor can take an Int32 value based on the number of ticks in the current time. However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers. The following example illustrates that two Random objects that are instantiated in close succession generate an identical series of random numbers..."
Wikipedia explains PRNGs
//Function to get random number
private static readonly Random random = new Random();
private static readonly object syncLock = new object();
public static int RandomNumber(int min, int max)
{
lock(syncLock) { // synchronize
return random.Next(min, max);
}
}
Copied directly from
You need something similar to this if you want the syntax you mention.
namespace MyRandom
{
public class Random
{
private static m_rand = new Random();
public static Next(int min, int max)
{
return m_rand.Next(min, max);
}
}
}
This should allow you to do Random.Next(1,100);
without having to worry about seeding.
Why not?
You need to create an instance because the way random numbers are generated is that previous answers affect subsequent answers. By default, the new Random()
constructor uses the current system time to "seed" the sequence, but it doesn't have to: you can pass your own number in if you like. In particular:
var rand = new Random(1234);
Console.WriteLine(rand.Next(0, 100));
Console.WriteLine(rand.Next(0, 100));
Console.WriteLine(rand.Next(0, 100));
Console.WriteLine(rand.Next(0, 100));
Will produce the same sequence of "random" number every time.
That means the Random
class needs to keep instance data (the previous answer, or "seed") around for subsequent calls.