I need to create random numbers between 0 and upto 2 so I am using:
//field level
private static Random _random = new Random();
//used in a method
_random.Next(0, 2)
My question is: will the sequence ever repeat / stop been random? Should I recreate (_random = new Random();
) every day?
Your code is fine as it is.
You do not need to create a new Random
object daily.
Note that Random
is not truly random, but produces a pseudo-random result.
If you check the 'remarks' section in the documentation you will find that System.Random is a pseudo-random generator.
This means in theory the sequence does eventually repeat. In practice it very much depends on what you're doing as to how much this matters. For example, the length of the sequence is such that no human will ever notice them repeating. On the otherhand, it's pretty useless for cryptography.
Edit to add: restarting daily won't make much difference. Either the pseudo-randomness is sufficient for you or you need to look into cryptographically secure way of generating random numbers.
Math.Random returns a 32-bit signed integer, it will repeat on the 2^32'nd call if you dont reseed. If you DO reseed it will repeat itself sooner.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With