Unique 4 digit random number in C#

//Generate RandomNo
public int GenerateRandomNo()
{
    int _min = 1000;
    int _max = 9999;
    Random _rdm = new Random();
    return _rdm.Next(_min, _max);
}

you need a 4 digit code, start with 1000


Use this code instead:

private Random _random = new Random();

public string GenerateRandomNo()
{
    return _random.Next(0, 9999).ToString("D4");
}

241 is a four digit number, if you use leading zeros: 0241.

Display the returned number with a format string like this:

String.Format("{0:0000}", n);

Tags:

C#

Random