I have read somewhere one of the main differences between Java and C++/C# is Java does something at Run-time and C# does something at compile-time. Is this true? If so could you explain this a bit more?
In C#, I created a function which takes in two inputs and returns a random number (called RandomNumber(int x, int y)
), using the Random Object. I then called this function twice in another function, expecting to get two difference values (two different random numbers). However, I kept getting same values, which baffled me, since I can do the same thing in Java and expect to get different numbers.
I then decided, to remove my function - RandomNumber(int x, int y) and call the Random inside my other function, show below.
Random random = new Random();
int randomNum;
int la;
randomNum = random.Next(1, 10);
numOne.Text = randomNum.ToString();
la = random.Next(1, 10);
This generates two different random numbers. Why is this the case?
The random number issue has nothing to do with compile-time or run-time. It has everything to do with where the Random class is instantiated.
The Random class doesn't really generate true random numbers. They are generated based on a mathematical formula that includes the current date/time and several other bits of data.
The following:
Random r = new Random(100)
for(int i = 0; i < 100; i++)
{
Console.WriteLine(r.Netc().ToString());
}
will generate a series of numbers that looks random.
This:
for(int i = 0; i < 100; i++)
{
Random r = new Random(100);
Console.WriteLine(r.Next().ToString());
}
will produce the same numbers for a few loops, then a new series of similar numbers for a few loops.
This is because of the formula. In the second example, each Random class is being created with very similar conditions, and will therefore produce the same number until the time changes enough to change the outcome.
However, with the first example, there is only one Random class and in subsequent iterations of the loop, it knows to produce a different number, because it knows it just generated one in the last loop.
If your code is calling a function that declared a new Random object and then uses Random.Next then in the scope of your function, Random is a new object on each call. Therefore, if your calls are within a few milliseconds, you'll get the same result.