Home »

Generate Random String in C#

Sometimes when I want to generate a random string and I forget this function, so I have to search on google or in my old project. It's quiet annoyed. So I post it here to make everything more convenient xD.
    private readonly Random random = new Random();
    private const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private string RandomString(int size)
    {
        StringBuilder strBuilder = new StringBuilder();

        for (int i = 0; i < size; i++)
        {
            strBuilder.Append(chars[random.Next(chars.Length)]);
        }
        return strBuilder.ToString();
    }
Because the random object is seeded from the system clock, so if you instantiate it inside the RandomString(), you will get the same result (string) when you call your method several times in quick succession. So you can put your Random instance outside the method as above code or you can do as follow for your Random object:
private static Random random = new Random((int)DateTime.Now.Ticks);
Hope this entry help you! If you found any mistake or error in this entry, please let me know. I'll try to fix that a.s.a.p. Any solution is highly appreciated! -Share2Learn-

No comments:

Post a Comment