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 and and is inclusive. - Multiply
fltwith and take theFloorof the result. This will return an integer (shift) that is between and and is inclusive. - Add the
shiftinteger to , which is the ASCII value of the character A. This will return an inclusive value between and , 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());}}
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved