Thursday, 31 January 2013

Generate Random Numbers of n length in C# / Asp.net

Sometimes it is required to generate  random numbers of length=n, so in that case the code below will help you to generate. Here by default it will generate random number of size 10 because i had used default value for the length=10 if no value are passed while calling it.


//Method to generate Random Numbers of n length
        public static string GenerateRandomNumbers(int length = 10)
        {
            //Initiate objects & vars 
            byte[ ] seed = Guid.NewGuid().ToByteArray();
            Random random = new Random(BitConverter.ToInt32(seed, 0));
            int randNumber = 0;
            //Loop ‘length’ times to generate a random number or character
            String randomNumber = "";
            for (int i = 0; i < length; i++)
            {
                randNumber = random.Next(48, 58);
               
randomNumber = randomNumber + (char)randNumber;
                //append random char or digit to
randomNumber string

            }
            return
randomNumber ;
        }


How to call the Method:
1)  string randomNumber= GenerateRandomNumbers( ); will generate a  random number of length=10.

2) string randomNumber= GenerateRandomNumbers(5); will generate a  random number of length=5.

 

No comments:

Post a Comment