
Note that Range is another example of a non-extension method. 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. The Enumerable class which is part of LINQ contains all of the extension methods we know and love. Next, let’s consider how the random characters are actually retrieved from the string.

If you need to generate random numbers for a security-critical section of code, consider using the RNGCryptoServiceProvider class instead. The seed that is used by the Random class when generating random numbers is based on the system clock.
#Generate random string code#
6WZT690E6D Allowed charactersĪs you can see from the code snippet, the local chars constant holds the set of possible characters.ĭepending 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.Īn instance of the Random class is used to pick a random number for the index position to select from the string of characters.Īs a side note, it is important to be aware that the Random class in C# is not truly random. Here is an example of the output produced by the above code. Var randomString = new string( Enumerable. / /// The desired length of the string /// The string which has been generated public static string GenerateRandomAlphanumericString( int length = 10)Ĭonst string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" / /// Generates a random alphanumeric string.

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

#Generate random string how to#
In this snippet, we see how to generate a random string with the Symfony string component.
