Random String Generation in C#
There are some programming problems that seem like they should be easy but aren’t (centering content in a DIV anyone?). Generating random unique strings is one of those things.
On a recent project we had the requirement to create several types of unique strings. A readable user code, item numbers and suggested strings for invite codes.
Random is Not Random
The first thing you learn when you start reading up on generating random numbers is that «Random» is not really random. When using the .Net Random class and providing the same seed value multiple instances will generate the same values. For example the following test will pass.
More ‘Random’ Solutions
In all our our scenarios for this project we don’t require the random string we generate to be globally unique or non-guessable. We will still need to ensure these values are unique in our database with the appropriate constraints. So, we can be a little more relaxed but I still wanted to see if there was something we could easily do beyond Random, but I also wanted some more insight into how good Random really is.
After some reading it appears that the simple alternative to using Random appears to be the RandomNumberGenerator.GetInt32 method introduced in .Net Core 3.
Two Solutions
To see if there was any real difference between random key generation using RandomNumberGenerator and the default Random constructor I created the following two generation methods.
Then I wrote a little unit test to see how many unique keys I could generate before we created a duplicate. 100,000 unique keys seemed like enough for my current usage.
With a sample size of 100,000 keys the test using RandomNumberGenerator would succeed almost every time and the test using Random would create a duplicate every 2 out of 3 attempts or more often.
That makes the winner for my usage the RandomNumberGenerator.
Real World
How did I begin using this?
When using this key generation code in my application to create short user codes I first abstracted the generation logic into an IKeyGenerator interface and then create a UserCodeGenerator that would generate the key and make sure it was unique in the database.
Conclusion
Generating unique strings as short as 4 characters requires keeping track of what codes have already been used. As we use more and more codes the likely hood of generating a code that has already been used increases and that will require a more complicated solution. That being said I think the task of generating a random string is easily solved using this method. It’s what I’ll be using moving forward.
Random String generator in C
I created this small function just to practice C code. It’s a simple random string generator.
The code seems to work ok. Any ideas, improvements or bugs?
I added the mySeed var so that if I call it twice with the same length it doesn’t give me the same exact string.
EDIT:
I have changed the code to this:
I know that in the sizeof(charset) you don’t have to use the () . You only need them when using sizeof with types, but it’s just out of habit.
5 Answers 5
Your function is nice but has a few issues, the main one being that it should not call srand . srand should be called elsewhere (eg in main ) just once. This seeds the random number generator, which need only be done once.
A minor issue is that string is badly named — charset might be better. It should be const and you then need not call strlen to find its length sizeof charset -1 is enough. For me, randomString is an unnecessarily long name.
On failing to allocate memory for the string, I would prefer to see a NULL return than an exit . If you want an error message, use perror , but perhaps in the caller, not here. I would be inclined to avoid the possibility of such an error but passing in the buffer and its length instead of allocating.
Some minor points: sizeof(char) is 1 by definition and using short for key is pointless — just use int . Also key should be defined where it is used and I would leave a space after the ; in the for loop definition.
Note also that using rand() % n assumes that the modulo division is random — that is not what rand promises.
Here is how I might do it:
Edit July 31 23:07UTC
Why would I write the function to take a buffer instead of allocating the string inside the function?
Returning dynamically allocated strings works fine. And if the memory is later freed there is no problem. But writing this sort of function is a great way to leak memory, for example if the caller doesn’t know the memory must be freed or forgets to free memory, or even if he frees it in the main path but forgets to free it in other paths etc.
Memory leaks in a desktop applications might not be fatal, but leaks in an embedded system will lead eventually to failure. This can be serious, depending upon the system involved. In many embedded systems, dynamic allocation is often not allowed or is at least best avoided.
Although it certainly is common not to know the size of strings or buffers at compile time, the opposite is also often true. It is often possible to write code with fixed buffer sizes. I always prefer this option if possible so I would be reluctant to use your allocating function. Perhaps it is better to add a wrapper to a non-allocating function for those cases where you really must allocate dynamically (for example when the random string has to outlive the calling context):
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.
- Determining which characters are allowed to be present in the random string.
- Selecting random characters from the set of possible characters.
- 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.
Here is an example of the output produced by the above code.
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
Генерация случайных строк в C#

Иногда полезно генерировать случайные строки, часто для тестирования программы, такой как сортировка строк.
Метод Random класса Next генерирует случайные числа. Чтобы сделать случайные слова, вы можете создать массив букв, а затем использовать объект Random, чтобы выбрать одну из букв для добавления к слову. Повторяйте до тех пор, пока слово не будет так долго, как вам нужно.
Введите количество слов и длину слова и нажмите «Перейти». Следующий код генерирует случайные слова и добавляет их в ListBox. (В реальной программе вы можете сделать что-то еще со словами, например, записать их в файл или поместить их в список или массив.)