C# Programming > Cryptography

C# Random String Generator

String Generator

A C# random string generator function creates a string that consists of random characters. Generating random strings in C# is useful for many things, for example for random password generators.

Like many things in .NET, the random string generator can be very complex or very simple. In this article the string generator will be relatively simple.

Generator Function

The random string generator should allow the programmer to choose some aspects of the final string: the length, and if the string is made up of lowercase letters, uppercase letters, numbers, and/or symbols. In fact our C# function will be able to create strings with any combination of those types of characters.

It almost makes sense to make this a C# class as opposed to only a function. This is because we are going to use the .NET Random class which has to be initialized. If we initialized the Random class every time we call the generator function, we would be forced to provide a seed for the random number generator, otherwise the string would not vary.

Thus making our C# string generator a class allows us to use the same Random object multiple times.

The flexibility of specifying the types of characters that will appear in the final string is important because there is no one use for a string generator. Some might use it for a random password generator while others may use it for CATPCHA systems.

Implementation

There are a few things to note on the C# implementation of our random string generator.

First of all, I explicitly declared each of the character groups (lowercase, uppercase, etc.) as constant strings. This allows the function to build a single "character pool" depending on the user specifications, and then randomly draw characters from said pool, which makes for a more compact C# function.

Also note that the entire string is initially declared as a character array, with individual characters being processed afterwards. This is a powerful technique that makes string processing faster and more efficiently than adding characters one at a time to the string.

Finally as mentioned before, at the base of the random string generator is .NET's Random class. This makes the function fast, but it also makes it pseudorandom (not really random). If you want to enhance the "randomness" of the function, I suggest you take a look at how to generate truly random numbers in C#.

Back to C# Article List