Why does this code produce the same output for both method calls? I would have assumed that because one method is a normal public method and is called from an instance then it would generate a different random number to the static method call as the instance is seperate from the one created for the static method call?
class ClassWithStaticMembers
{
public static int ReturnAnIntStatic()
{
Random random = new Random();
return random.Next();
}
public int ReturnAnInt()
{
Random random = new Random();
return random.Next();
}
}
class Program
{
static void Main(string[] args)
{
ClassWithStaticMembers classWithStaticMembers = new ClassWithStaticMembers();
//We can do this because the method is declared static.
Console.WriteLine(ClassWithStaticMembers.ReturnAnIntStatic());
//This can be used as we have not declared this method static
Console.WriteLine(classWithStaticMembers.ReturnAnInt());
Console.ReadKey();
}
}
Output is as follows:
12055544
12055544
Can someone explain why using a method call from an instance of a class procuces the same result as a method call from a static method? Are the instances generated for the method calls not different?
EDIT: Further to this. Is the instance of ClassWithStaticMembers used to call the public method seperate to the static call. By which I mean would the compiler use the same instance again if it recognises I am making a call to the same class later in the file?
That’s because the Random is by default seeded by the current ticks and since both methods are called at almost the same time, they will produce the same numbers. This is explained in the documentation:
Put a sleep between the 2 method calls to observe the difference:
Or use a different constructor for the Random class to seed them differently. Or simply use the same static instance of a
Randomclass:That’s the reason why you should never use the Random class when you require real randomness and not pseudo random numbers. For example in cryptography you should use the RNGCryptoServiceProvider instead of the
Randomclass. Once you know the initial seed value that was used to instantiate the Random class, you can predict all the numbers this class is going to generate.