10
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#?

Ry-
  • 218,210
  • 55
  • 464
  • 476
vini
  • 4,657
  • 24
  • 82
  • 170
  • see the following link: http://stackoverflow.com/questions/13539974/random-number-generator-c-sharp[enter link description here][1] [1]: http://stackoverflow.com/questions/13539974/random-number-generator-c-sharp – Rayhan.iit.du Jun 18 '13 at 03:38
  • 8
    For your purposes, is **0004** a 4-digit number? Is **00000008** an 8-digit number? Does it matter that those are included? – doppelgreener Jun 18 '13 at 03:57

4 Answers4

34

Start at the smallest 4-digit number, end at the smallest 9-digit number (exclusive):

int password = random.Next(1000, 100000000);
Ry-
  • 218,210
  • 55
  • 464
  • 476
3

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));
}
AgentFire
  • 8,944
  • 8
  • 43
  • 90
3

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');
Pinch
  • 4,009
  • 8
  • 40
  • 60
  • 1
    Why not: `Random RandomPIN = new Random(); var RandomPINResult = RandomEASPIN.Next(0, 9999).ToString("D4");` – Mir Dec 29 '14 at 19:38
2

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

  • It uses the classical random value, but the author was aware that a seed is needed to get real random values. So the next step is just to generate an int from an interval and make sure it's formatted with pre-pending (pad left) zeros (4 digit length). – baHI Mar 27 '17 at 10:52