How to generate a random string with C#

On occasion, during day-to-day programming, the problem I am working on requires the generation of a random sequence of characters.

For example, when dealing with some sort of account entity, the account might require a unique account reference to be specified upon its creation. Considering this scenario, it would be inconvenient for the end-user to have to conjure up a unique reference for each new account.

In this article, I present a concise solution to this problem and explain how it works.

Generating the randomness

Conceptually, there are three key things to think about when designing the solution and they are as follows.

  1. Determining which characters are allowed to be present in the random string.
  2. Selecting random characters from the set of possible characters.
  3. Combining the chosen characters into the final result.

The implementation I have included below creates an alphanumeric string consisting solely of upper case characters and numbers.

/// <summary>
/// Generates a random alphanumeric string.
/// </summary>
/// <param name="length">The desired length of the string</param>
/// <returns>The string which has been generated</returns>
public static string GenerateRandomAlphanumericString(int length = 10)
{
    const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
 
    var random       = new Random();
    var randomString = new string(Enumerable.Repeat(chars, length)
                                            .Select(s => s[random.Next(s.Length)]).ToArray());
    return randomString;
}

Here is an example of the output produced by the above code.

6WZT690E6D

Allowed characters

As you can see from the code snippet, the local chars constant holds the set of possible characters.

Depending on the use-case, and if a more random string is required, the code could be amended to support other characters by appending them to the chars variable.

e.g. !$%_ etc.

Character selection

An instance of the Random class is used to pick a random number for the index position to select from the string of characters.

As a side note, it is important to be aware that the Random class in C# is not truly random. The seed that is used by the Random class when generating random numbers is based on the system clock. If you need to generate random numbers for a security-critical section of code, consider using the RNGCryptoServiceProvider class instead.

Next, let’s consider how the random characters are actually retrieved from the string.

The Enumerable class which is part of LINQ contains all of the extension methods we know and love. The Repeat method within the Enumerable class is fairly unique, in that it is one of the only methods that it is not an extension method.

Note that Range is another example of a non-extension method.

Repeat accepts a generic element argument and an integer count parameter and it returns an IEnumerable collection of the specified generic type.

For our scenario, the element passed to the Repeat method is a string i.e. the chars string constant. The returned value is a collection of strings i.e. a collection containing 10 copies of the chars string constant.

After getting the collection of string elements back the Select method is called to project each string element into a character array. The ‘Func’ selector which is passed into Select chooses a character at a random index within each string element in the collection of strings which was generated by the Repeat function.

Character combination

Lastly, the resulting collection of randomly chosen characters are passed to the string constructor which combines the characters into the final string.

There’s quite a bit going on for such a small amount of code. That’s the power of LINQ!

What about duplicates?

If need be, the code could be extended to check a datastore to ensure that the string is unique before returning from the method.

To implement this we could perform a lookup to check if there is an existing account entity with a reference that matches the randomly generated string. If a matching account exists, we would then generate a new random string and do a further lookup.

The above steps would need to be carried out in a loop (preferably with a loop limit) until we have determined that the string is unique.


I hope you enjoyed this post! Comments are always welcome and I respond to all questions.

If you like my content and it helped you out, please check out the button below 🙂

Comments

pulkitsoft

Please provide code ensure that no duplicate string returning.

July 1, 2021

Jonathan Crozier

Hi there, the answer to your question will depend on a number of different factors such as what datastore and ORM library you are using. Do you use Entity Framework? I can send you a message with some sample code once I know the answer to this.

July 1, 2021

Dave

Thanks for a well explained solution!
This let me away with generating a one time only password for user creation / reset.

September 16, 2021

Jonathan Crozier

You’re most welcome, Dave. Glad it helped!

September 16, 2021