Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique 4 digit random number in C#

Tags:

c#

random

I want to generate an unique 4 digit random number. This is the below code what I have tried:

Code for generating random number

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

The problem is I have received a random no with value 241 which is not a 4 digit number. Is there any problems with the code?

like image 548
ksg Avatar asked Nov 17 '15 05:11

ksg


3 Answers

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

like image 167
Brij Raj Singh - MSFT Avatar answered Nov 11 '22 16:11

Brij Raj Singh - MSFT


Use this code instead:

private Random _random = new Random();

public string GenerateRandomNo()
{
    return _random.Next(0, 9999).ToString("D4");
}
like image 40
Moon Avatar answered Nov 11 '22 17:11

Moon


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);

like image 9
x0n Avatar answered Nov 11 '22 17:11

x0n