Click here to Skip to main content
Click here to Skip to main content

Tagged as

C# Random String Generator

, 18 Apr 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
A C# class that can generate random strings and supports customisation.


Using this class you can generate random strings like passwords and identificators, but the main feature is that you can customize it to fit your needs. To do that you don't need to modify the code, it's enough to set some settings and you'll change the behavior of the generator.


I was looking for a C# class which could generate unique random strings for identificators, but I couldn't found one that fits all my needs such as minimal number of characters of each type (upper case letters, lower case letters, numbers and special characters) or usage of each character only once. So I've decided to code a class where you can set the following:

  1. Four character sets (UpperCase, LowerCase, Numeric, and Special characters)
  2. Set your own character set
  3. Minimal number of each type of the characters
  4. Pattern driven string generation
  5. Unique string generation
  6. Using each character only once


The code, in general, is pretty big and you can download it if you want, so I'll describe only the essential parts. 


  • Green - public methods
  • Red - private methods
  • Blue - internal data

The user has three options: Generate a string of a fixed size, string of a variable size, or pattern driven string generation. Each of them will later call the general GenerateString method that will check exceptional situations and call one of three algorithms to generate a string (just like Strategy pattern does). At the end it will check if this string is unique and if we need a unique string and the generated string is not unique, it'll then recall itself (recursively, so you can get a stack overflow exception while generating a lot of small strings with a lot of restrictions). I'm using RNGCryptoServiceProvider to get random numbers, but you can change it to normal Random if you want the generation to work faster.

This method generates a string by deciding which algorithm will be used.

private string GenerateString(int length)
    if (length == 0)
       throw new ArgumentException("You can't generate a string of a zero length");
    if (!UseUpperCaseCharacters && !UseLowerCaseCharacters && !UseNumericCharacters && !UseSpecialCharacters)
       throw new ArgumentException("There should be at least one character set in use");
    if (!RepeatCharacters && (CurrentGeneralCharacters.Length < length))
       throw new ArgumentException("There is not enough characters to create a string without repeats");
    string result = ""; // This string will contain the result
    if (PatternDriven)
       // Using the pattern to generate a string
       result = PatternDrivenAlgo(Pattern);
    else if (MinUpperCaseCharacters == 0 && MinLowerCaseCharacters == 0 &&
             MinNumericCharacters == 0 && MinSpecialCharacters == 0)
       // Using the simpliest algorithm in this case
       result = SimpleGenerateAlgo(length);
       // Paying attention to limits
       result = GenerateAlgoWithLimits(length);
       // Support for unique strings
       // Recursion, but possibility of the stack overflow is low for big strings (> 3 chars).
       if (UniqueStrings && ExistingStrings.Contains(result))
           return GenerateString(length);
       AddExistingString(result); // Saving history
       return result;

The simplest used algorithm for string generation. It's called only for all limits (e.g., MinUpperCaseCharacters equals to 0).

private string SimpleGenerateAlgo(int length)
   string result = "";
   // No special limits
   for (int i = 0; i < length; i++)
      char newChar = CurrentGeneralCharacters[GetRandomInt() % CurrentGeneralCharacters.Length];
      if (!RepeatCharacters && result.Contains(newChar))
            newChar = CurrentGeneralCharacters[GetRandomInt() % CurrentGeneralCharacters.Length];
         } while (result.Contains(newChar));
         result += newChar;
   return result;

The algorithm of the string generation paying attention for limits.

private string GenerateAlgoWithLimits(int length)
  // exceptional situations
  if (MinUpperCaseCharacters + MinLowerCaseCharacters +
    MinNumericCharacters + MinSpecialCharacters > length)
    throw new ArgumentException("Sum of MinUpperCaseCharacters, MinLowerCaseCharacters," +
    " MinNumericCharacters and MinSpecialCharacters is greater than length");
  if (!RepeatCharacters && (MinUpperCaseCharacters > CurrentUpperCaseCharacters.Length))
    throw new ArgumentException("Can't generate a string with this number of MinUpperCaseCharacters");
  if (!RepeatCharacters && (MinLowerCaseCharacters > CurrentLowerCaseCharacters.Length))
    throw new ArgumentException("Can't generate a string with this number of MinLowerCaseCharacters");
  if (!RepeatCharacters && (MinNumericCharacters > CurrentNumericCharacters.Length))
    throw new ArgumentException("Can't generate a string with this number of MinNumericCharacters");
  if (!RepeatCharacters && (MinSpecialCharacters > CurrentSpecialCharacters.Length))
    throw new ArgumentException("Can't generate a string with this number of MinSpecialCharacters");
  int AllowedNumberOfGeneralChatacters = length - MinUpperCaseCharacters - MinLowerCaseCharacters
  - MinNumericCharacters - MinSpecialCharacters;
  string result = "";
  // generation character set in order to support unique characters
  List<char> Characters = new List<char>();
  // adding chars to an array
  for (int i = 0; i < MinUpperCaseCharacters; i++)
  for (int i = 0; i < MinLowerCaseCharacters; i++)
    Characters.Add(GetRandomCharFromArray(LowerCaseCharacters, Characters));
  for (int i = 0; i < MinNumericCharacters; i++)
    Characters.Add(GetRandomCharFromArray(NumericCharacters, Characters));
  for (int i = 0; i < MinSpecialCharacters; i++)
    Characters.Add(GetRandomCharFromArray(SpecialCharacters, Characters));
  for (int i = 0; i < AllowedNumberOfGeneralChatacters; i++)
    Characters.Add(GetRandomCharFromArray(CurrentGeneralCharacters, Characters));
  // generating result
    for (int i = 0; i < length; i++)
      int position = GetRandomInt() % Characters.Count;
      char CurrentChar = Characters[position];
      result += CurrentChar;
    return result;

CurrentGeneralCharacters is generated automatically using four existing character sets: UseUpperCaseCharacters, UseLowerCaseCharacters, UseNumericCharacters, and UseSpecialCharacters. I believe that it's faster to generate it once (at the stage of parametrisation) then to regenerate it each time it's necessary.

The last string generation algorithm generates a string based on the pattern. It simply replaces the pattern's letters by random symbols from the corresponding set. And sure it pays attention to the RepeatCharacters flag.

private string PatternDrivenAlgo(string Pattern)
    string result = "";
    List<char> Characters = new List<char>();
    foreach (char character in Pattern.ToCharArray())
        char newChar = ' ';
        switch (character)
            case 'L':
                newChar = GetRandomCharFromArray(CurrentUpperCaseCharacters, Characters);
            case 'l':
                newChar = GetRandomCharFromArray(CurrentLowerCaseCharacters, Characters);
            case 'n':
                newChar = GetRandomCharFromArray(CurrentNumericCharacters, Characters);
            case 's':
                newChar = GetRandomCharFromArray(CurrentSpecialCharacters, Characters);
            case '*':
                newChar = GetRandomCharFromArray(CurrentGeneralCharacters, Characters);
                throw new Exception("The character '" + character + "' is not supported");
        result += newChar;
    return result;

Using the code

To start using it you need to create an instance of a class and call Generate like this:

Console.WriteLine("Fixed size");
RandomStringGenerator RSG = new RandomStringGenerator();
for (int i = 0; i < 5; i++)

Console.WriteLine("Variable size");
RSG = new RandomStringGenerator();
for (int i = 0; i < 5; i++)

Console.WriteLine("Using pattern");
RSG = new RandomStringGenerator();
for (int i = 0; i < 5; i++)

Console.WriteLine("Using only letters and numbers");
RSG = new RandomStringGenerator();
// Or we can use the constructor
RSG.UseSpecialCharacters = false;
for (int i = 0; i < 5; i++)

Console.WriteLine("Using only special characters and numbers");
RSG = new RandomStringGenerator();
// Or we can use the constructor
RSG.UseUpperCaseCharacters = false;
RSG.UseLowerCaseCharacters = false;
for (int i = 0; i < 5; i++)
Console.WriteLine("Using your own alphabet");
RSG = new RandomStringGenerator(false,true,true,false);
// Or we can use the constructor
RSG.LowerCaseCharacters = "абвгдежзиклмнопрстуфхчшщюяьъ".ToCharArray();
for (int i = 0; i < 5; i++)

Console.WriteLine("Using special limits");
RSG = new RandomStringGenerator();
RSG.MinLowerCaseCharacters = 2;
RSG.MinSpecialCharacters = 20;
for (int i = 0; i < 5; i++)

Console.WriteLine("Using each character only once");
RSG = new RandomStringGenerator();
RSG.MinLowerCaseCharacters = 25;
RSG.RepeatCharacters = false;
for (int i = 0; i < 5; i++)

Console.WriteLine("Using custom alphabet, pattern and unique chars");
RSG = new RandomStringGenerator();
RSG.LowerCaseCharacters = "абвгдежзиклмнопрстуфхчшщюяьъ".ToCharArray();
RSG.RepeatCharacters = false;
for (int i = 0; i < 5; i++)

Console.WriteLine("Unique strings test");
RSG = new RandomStringGenerator(false,false,true,false); // numbers only
RSG.UniqueStrings = true;
for (int i = 0; i < 9; i++)

This gives the following result:

Fixed size


Variable size


Using pattern


Using only letters and numbers


Using only special characters and numbers


Using your own alphabet


Using special limits


Using each character only once


Using custom alphabet, pattern and unique chars


Unique strings test

So there are some examples like:

  1. Fixed size string generation
  2. Variable size string generation
  3. String generation using a pattern (L - for upper case letter, l - for lower case letter, n - for number, s - for special character and * - for any character (from all sets)
  4. String generation using only letters and numbers
  5. String generation using only numbers and special characters
  6. Using a custom alphabet for the generation
  7. Using minimal limits for string generation
  8. Using each character only once during the generation
  9. Using multiple settings
  10. Unique strings test


  • Version 1.1: Some code explanations and optimizations were made. Thanks to the comments.
  • Version 1.0: Initial release.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author


France France
I'm currently a master student at the University of Maine in France. I'm studying computer science and in my spare time I enjoy programming using such languages as C,C++,C#,Java and Ruby.

Comments and Discussions

QuestionToo bad for huge number of unique string Pinmemberfeeeper1-Jan-15 8:02 
GeneralMy vote of 3 Pinmemberfeeeper1-Jan-15 7:58 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun24-Sep-14 19:55 
QuestionPerfect PinmemberMember 109973066-Aug-14 22:34 
Questionrequired code Pinmembermrrocker9828-Jun-14 23:31 
Questionrequest Pinmembermrrocker9827-Jun-14 9:34 
AnswerRe: request PinmemberPIEBALDconsult27-Jun-14 10:16 
GeneralRe: request Pinmembermrrocker9828-Jun-14 23:12 
QuestionSimplement bravo ! Mais il faut peut-etre avoir la culture française pour en mesurer la beauté du code. Pinmemberche@free.fr19-Apr-14 7:24 
GeneralMy vote of 5 PinprofessionalBrian A Stephens12-Nov-13 8:28 
GeneralMy vote of 5 PinprofessionalPrasad Khandekar24-Jun-13 21:48 
QuestionNo recursion? PinmemberGeorge Swan23-Apr-13 10:52 
GeneralMy vote of 5 Pinmemberfredatcodeproject19-Apr-13 6:43 
GeneralThank you for this Article Pinmemberskylinegtr3519-Apr-13 2:12 
Generalthank for your article Pinmemberbenjamin9x18-Apr-13 19:43 
QuestionConfusing Article PinmemberYvar Birx18-Apr-13 10:43 
AnswerRe: Confusing Article Pinmemberbrol.sergii19-Apr-13 10:58 
GeneralRe: Confusing Article PinmemberYvar Birx20-Apr-13 6:32 
SuggestionEasier way PinmemberMember 383711819-Jul-12 5:36 
GeneralRe: Easier way Pinmemberbrol.sergii19-Jul-12 10:55 
QuestionPath.GetRandomFileName() (from System.IO) Pinmembernewton.saber19-Jul-12 4:17 
AnswerRe: Path.GetRandomFileName() (from System.IO) Pinmemberbrol.sergii19-Jul-12 10:37 
GeneralHuh? PinmemberVitaly Tomilov18-Jul-12 10:12 
GeneralRe: Huh? Pinmemberbrol.sergii18-Jul-12 10:21 
I mean you can do it without modifying the code of the class. Just by setting parameters.
GeneralRe: Huh? PinmemberVitaly Tomilov18-Jul-12 10:25 
GeneralRe: Huh? Pinmemberbrol.sergii18-Jul-12 10:32 
GeneralRe: Huh? PinmemberVitaly Tomilov24-Oct-12 7:23 
GeneralRe: Huh? Pinmemberbrol.sergii24-Oct-12 12:01 
GeneralRe: Huh? PinmemberRoman Alifanov19-Nov-12 2:51 
Questionfair PinmemberCIDev18-Jul-12 5:18 
GeneralRepetition PinmemberJohn Brett18-Jul-12 2:17 
GeneralRe: Repetition Pinmemberbrol.sergii18-Jul-12 10:14 
QuestionSpacing Pinmembercjb11017-Jul-12 22:29 
AnswerRe: Spacing Pinmemberbrol.sergii18-Jul-12 10:18 
GeneralThoughts PinmemberPIEBALDconsult17-Jul-12 16:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150123.1 | Last Updated 18 Apr 2013
Article Copyright 2012 by brol.sergii
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid