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#?
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#?
Start at the smallest 4-digit number, end at the smallest 9-digit number (exclusive):
int password = random.Next(1000, 100000000);
You could also make a method:
public static int GetRandom(int minDigits, int maxDigits)
{
if (minDigits < 1 || minDigits > maxDigits)
throw new ArgumentOutOfRangeException();
return (int)random.Next(Math.Pow(10, minDigits - 1), Math.Pow(10, maxDigits - 1));
}
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');
new Random(Guid.NewGuid().GetHashCode()).Next(0, 9999).ToString("D4")