C#: Get a random string

Random String methods for C#

Background:

Sometimes, we need to generate some random strings for testing purpose. When I met this situation, I was surprised that C# has no such built-in methods inside its Random Class. So I had to implemented them as extension methods.

Solution:

    #region Random's Extension
    public static class RandomExtension
    {
        /// 
        /// Returns a random character between the start and end characters specified
        /// 
        /// 
        /// The start of the range that the next random character will be generated from
        /// The end of the range that the next random character will be generated from
        /// A character whose ASCII code greater than or equal to the start's and less than or equal to the end's
        public static char NextChar(this Random rnd, char start = 'a', char end = 'z')
        {
            int startCode = (int)start;
            int endCode = (int)end + 1;
            if (startCode <= endCode)
            {
                int code = rnd.Next(startCode, endCode);
                return (char)code;
            }
            else
            {
                throw new ArgumentException("The 'start' character can NOT be greater than the 'end' charcater", "start");
            }
        }

        /// 
        /// Returns a random character among a set of specified characters
        /// 
        /// 
        /// A set of the characters that the new random character will be generated from
        /// A character from the specified character set
        public static char NextChar(this Random rnd, char[] candidates)
        {
            if (candidates.Length > 0)
                return candidates[rnd.Next(0, candidates.Length)];
            else
                throw new ArgumentException("Must specify at least 1 character in the array (char[] candidates).", "candidates");
        }

        /// 
        /// Returns a random letter character ({'a' - 'z'} + {'A' - 'Z'})
        /// 
        /// 
        /// A character of the 26 English letters ignoring case.
        public static char NextLetter(this Random rnd)
        {
            return rnd.NextChar(new char[] { rnd.NextChar('a', 'z'), rnd.NextChar('A', 'Z') });
        }

        /// 
        /// Returns a random letter string (a string contains only letters, no other special characters) with customized length
        /// 
        /// 
        /// The length that the random string will be in
        /// A string contains only letters.
        public static string NextLetterString(this Random rnd, int length = 10)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < length; i++)
            {
                sb.Append(rnd.NextLetter());
            }
            return sb.ToString();
        }
    }
    #endregion

Remark:

After I published this post, I just found out that I had already posted this one half a year ago which I totally forgot, and I was amazed by their similarities. The words I used in these 2 posts are almost the same! That indicates I hadn't changed a lot in recent half year. :)

I will keep this post other than update the old one, because I think the similarity is very interesting.

Add comment

Loading