I want to generate an unique 4 digit random number. This is the below code what I have tried:
Code for generating random number
//Ge
I suggest to create new list and check if this list contains any of number
var IdList = new List<int>();
do
{
billId = random.Next(1, 9000);
} while (IdList.Contains(billId));
IdList.Add(billId);
use: int _min = 1000;
or use leading 0 in case if you want 0241
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);
You can consider something like this.
int length = 4;
int number = 50;
string asString = number.ToString("D" + length);
The above code gives the result 0050.
Similarly you can try converting to string and verify.
Random generator = new Random();
string number = generator.Next(1, 10000).ToString("D4");
Expanding on the answer from brij but with 0000 to 9999 rather than 1000 to 9999
string formatting = "0000"; //Will pad out to four digits if under 1000
int _min = 0;
int _max = 9999;
Random randomNumber = new Random();
var randomNumberString = randomNumber.Next(_min, _max).ToString(formatting);
or if you want to minimalize lines:
Random randomNumber = new Random();
var randomNumberString = randomNumber.Next(0, 9999).ToString("0000");