Often we have looking for generating random number or random string for some requirement such as captcha validation, sending password in email etc. Here I’m creating a simple example on how to generate random number and random string. Let’s have a look.

using System;
using System.Text;
namespace RandomNumberString
{
    /// <summary>
    /// Generate Random Number and String
    /// </summary>
    class NumbeString
     {
       Random random = new Random();
       StringBuilder builder = new StringBuilder();
       /// <summary>
       /// Method for generate random number
       /// </summary>
       public void RandomNumber()
        {
             Console.WriteLine("Random Number \n" + random.Next(10000));
        }
        /// <summary>
        /// method for generate random string with lower and upper case
        /// </summary>
        /// <param name="size"></param>
        /// <param name="lowerCase"></param>
       public void RandomString()
       {
           char ch;
           for (int i = 0; i < 4; i++)
           {
               ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));// Upper case char
               builder.Append(ch);
               ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 97)));// Lower case char
               builder.Append(ch);
           }
           Console.WriteLine("Random String \n" + builder.ToString());
       } 
    }
    /// <summary>
    /// class for define main method
    /// </summary>
    class String
    {
       static void Main(string[] args)
        {
            NumbeString ns = new NumbeString();
            ns.RandomNumber();
            ns.RandomString();
            Console.ReadLine();
        }
    }
}

Output

 

Build application and execute program. Every Execution new Random number and string will be display. For example

Random Number

2918

Random String

NvPfTaKu

  Modified On Sep-18-2014 01:24:03 PM

Leave Comment