Thursday, October 23, 2008

Random String Generator

I encountered the problem where I needed to build a lot of controls at runtime and of course I needed the to have a name. I decided to use a Random String builder and here is what I cam up with:

 public static string RandomString(this String str, int size, bool lowerCase)
        {
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            char ch;
            for (int i = 0; i < size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(2 * random.NextDouble() + 28)));
                builder.Append(ch);
            }
            if (lowerCase)
                return builder.ToString().ToLower();
            return builder.ToString();
        }

* One small side note is that the 2 and the 28 in the sample have no correlation to the result, I just wanted a completely random result.

No comments: