Related Tags

generate
random
string
c#

How to generate a random string in C#

Generating a random string in C# uses the same concepts that are used to generate a random number in C#. The StringBuilder class and the NextDouble() method in the Random class are used to generate a random string.

Algorithm

• Use the Random.NextDouble() method to generate a float (flt) that is between $0.0$ and $1.0$ and is inclusive.
• Multiply flt with $25$ and take the Floor of the result. This will return an integer (shift) that is between $0$ and $25$ and is inclusive.
• Add the shift integer to $65$, which is the ASCII value of the character A. This will return an inclusive value between $65$ and $90$, which will be the ASCII value of some character. Converting that value to a character will return an uppercase character.
• Repeat the above steps​ as required to obtain a randomly generated string.

Code

The code snippet below illustrates the algorithm described above:

using System.Text;
using System;
class GenerateRandomString
{
static void Main()
{
int length = 7;

// creating a StringBuilder object()
StringBuilder str_build = new StringBuilder();
Random random = new Random();

char letter;

for (int i = 0; i < length; i++)
{
double flt = random.NextDouble();
int shift = Convert.ToInt32(Math.Floor(25 * flt));
letter = Convert.ToChar(shift + 65);
str_build.Append(letter);
}
System.Console.WriteLine(str_build.ToString());
}
}

RELATED TAGS

generate
random
string
c#