Sunday, April 14, 2019

Code Recipe: How to generate random alpha numeric string in C# .Net



This C# .Net code is from the Code Recipes series of Test Automation TV YouTube Channel.
The full explanation of the code is available in the video.


public string GenerateRandomString(int stringLength = 10)
        {
            if(stringLength < 1)
            {
                stringLength = 10;
            }

            StringBuilder retVal = new StringBuilder();

            Random rNumberSmallCapsOrSpecialChar = new Random(DateTime.Now.Millisecond);

            int typeOfCharToGenerate = 1;

            for (int i = 0; i < stringLength; i++)
            {
                typeOfCharToGenerate = rNumberSmallCapsOrSpecialChar.Next(1, 4);

                switch (typeOfCharToGenerate)
                {
                    case 1:// generate a number
                        retVal.Append(rNumberSmallCapsOrSpecialChar.Next(0, 9));
                        break;
                    case 2: // generate a small alphabet
                        retVal.Append((char)rNumberSmallCapsOrSpecialChar.Next(97, 122));
                        break;
                    case 3: // generate a capital alphabet
                        retVal.Append((char)rNumberSmallCapsOrSpecialChar.Next(65, 90));
                        break;
                    case 4: // special char
                        retVal.Append((char)rNumberSmallCapsOrSpecialChar.Next(33, 46));
                        break;
                }
            }

            return retVal.ToString();
        }


  [TestMethod]
        public void MakeRandomString()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(GenerateRandomString());
                System.Threading.Thread.Sleep(10);
            }
        }

This video also shows how to use Visual Studio 2019 test explorer to run tests.
Other topics included are


  1. typecasting of an int to a char in C#
  2. Using StringBuild.Append method
  3. Using Random class and Next method
  4. Specifying default parameter values in methods
  5. Using Sleep method call



No comments:

Post a Comment

Feel free to talk back...