I created a Random
class object named x
within a for
loop and called x.next(1,7)
which should return a variable between 1
and 6
, both object creation and x.next()
function is placed inside the for loop which executes 5
times instead of returning random variables it returns same value in each iteration
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
for(int i=1;i<=5;i++)
{
Random x = new Random();
Console.WriteLine( x.Next(1,7));
}
}
}
}
My output is as follows
5
5
5
5
5
When i place the object declaration outside the loop it returns random variables in each iteration
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Random x = new Random();
for(int i=1;i<=5;i++)
{
Console.WriteLine( x.Next(1,7));
}
}
}
}
This time my output is
4
5
9
3
1
and also works when x
is declared as static variable of class Program as follows
using System;
namespace ConsoleApplication1
{
class Program
{
static Random x = new Random();
static void Main(string[] args)
{
for(int i=1;i<=5;i++)
{
Console.WriteLine( x.Next(1,7));
}
}
}
}
now output is
4
7
3
7
9
But i want to know why it returned same values when object is declared inside the loop and what happens when object variable is declared as static??