Create a random number as a string with a maximum length. - CSharp System

CSharp examples for System:Random

Description

Create a random number as a string with a maximum length.

Demo Code


using System.Text;
using System.Security.Cryptography;
using System;/*from w ww .  jav  a2  s . c  o m*/

public class Main{

        /// <summary>
        /// Create a random number as a string with a maximum length.
        /// </summary>
        /// <param name="length">Length of number</param>
        /// <returns>Generated string</returns>
        public static string GeneratRandomNumber(int length)
        {
            if (length > 0)
            {
                var sb = new StringBuilder();

                var rnd = SeedRandom();
                for (int i = 0; i < length; i++)
                {
                    sb.Append(rnd.Next(0, 9).ToString());
                }

                return sb.ToString();
            }

            return string.Empty;
        }
        private static Random SeedRandom()
        {
            return new Random(Guid.NewGuid().GetHashCode());
        }
}

Related Tutorials