Unique 4 digit random number in C#

前端 未结 11 2012
故里飘歌
故里飘歌 2021-01-01 13:27

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         


        
11条回答
  •  说谎
    说谎 (楼主)
    2021-01-01 13:49

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

提交回复
热议问题