Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

3 digit random number in C#

Tags:

c#

.net

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..

like image 549
dotnet-practitioner Avatar asked Jan 22 '13 18:01

dotnet-practitioner


People also ask

How do you generate a random 3 digit number in C#?

You should use this to get a number of 3 digits (less than 1000). Random rand = new Random(); // <-- Make this static somewhere const int maxValue = 999; string number = rand. Next(maxValue + 1). ToString("D3");

What is random function in C?

Description. The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX. RAND_MAX is a constant whose default value may vary between implementations but it is granted to be at least 32767.


2 Answers

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 Random or RandomNumberGenerator (which is more secure).

For example, once you've got an instance of Random, you could use:

int value = rng.Next(1000);
string text = value.ToString("000");

(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:

  • You don't want to create a new instance each time you use it; that would also be time based unless you specify a seed
  • It's not thread-safe

So ideally you probably want one per thread. My article on randomness talks more about this and gives some sample code.

like image 145
Jon Skeet Avatar answered Sep 28 '22 04:09

Jon Skeet


int r = (new Random()).Next(100, 1000);
like image 23
Lee Avatar answered Sep 28 '22 02:09

Lee