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
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.