Is there a better way to generate 3 digit random number than the following:
var now = DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture);
string my3digitrandomnumber = now.Substring(now.Length - 7, 3);
Thanks..
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.
Yes – your current code isn’t random at all. It’s based on the system time. In particular, if you use this from several threads at the same time – or even several times within the same thread in quick succession – you’ll get the same number each time.
You should be using
RandomorRandomNumberGenerator(which is more secure).For example, once you’ve got an instance of
Random, you could use:(That’s assuming you want the digits as text. If you want an integer which is guaranteed to be three digits, use
rng.Next(100, 1000).)However, there are caveats around
Random:So ideally you probably want one per thread. My article on randomness talks more about this and gives some sample code.