Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a 4–8 digit random number

Tags:

c#

random

Random random = new Random();
int password = random.Next(10000);

This generates 2-digit and 3-digit numbers also. How do I generate a 4–8 digit random number in C#?

like image 324
vini Avatar asked Jun 18 '13 03:06

vini


2 Answers

To cover all your bases (numbers under 1000 such as 0002)

Random RandomPIN = new Random();
var RandomPINResult = RandomPIN.Next(0, 9999).ToString();
RandomPINResult = RandomPINResult.PadLeft(4, '0');
like image 159
Pinch Avatar answered Oct 17 '22 21:10

Pinch


new Random(Guid.NewGuid().GetHashCode()).Next(0, 9999).ToString("D4")

like image 41
Vladimir G. Nosov Avatar answered Oct 17 '22 20:10

Vladimir G. Nosov