Random ran = new Random();
byte tmp = (byte)ran.Next(10);
Is there an alternative to this code?
It does not seem to have fully random behavior.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There are multiple reasons for why this could occur. One common problem is to create multiple instances of the
Randomclass within a program. When using theRandomclass you should only create one instance and generate numbers from that. The article Create better random numbers in C# has a good explanation of why and explains why not doing this could lead to a problem.Another common scenario is accessing the
Randomclass object from multiple threads.System.Randomis not thread safe (see the Remarks section of the documentation forRandom) and thus can lead to unexpected and unwanted behavior. If using it in a multi-threaded environment then you need to be sure to use some form of locking to prevent multiple threads trying to generate random numbers at the same time.For higher degrees of security and randomness you can use a cryptographically secure random number generator like
System.Security.Cryptography.RNGCryptoServiceProvider. Note that using a more secure random number generator will incur a performance penalty in comparison with
System.Random.If you don’t need something cryptographically secure, but still want something that is more “random” than the
Randomclass you can explore using other PRNG’s such as Mersenne Twister. There are lots of options, each with different characteristics and performance profiles. Which you choose is heavily dependent on your goal.