Lastly, the resulting collection of randomly chosen characters are passed to the string constructor which combines the characters into the final string. 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. a collection containing 10 copies of the chars string constant.Īfter getting the collection of string elements back the Select method is called to project each string element into a character array. The returned value is a collection of strings i.e. Repeat accepts a generic element argument and an integer count parameter and it returns an IEnumerable collection of the specified generic type.įor our scenario, the element passed to the Repeat method is a string i.e. 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.