random string generation - two generated one after another give same results

前端 未结 5 675
无人共我
无人共我 2020-12-21 15:35

I have a simple piece of code:

public string GenerateRandomString()
        {
            string randomString = string.Empty;
            Random r = new Rand         


        
5条回答
  •  渐次进展
    2020-12-21 16:22

    The above answers are correct. I would suggest the following changes to your code though:

    1) I would suggest using a StringBuilder instead of appending to the string all the time. Strings are immutable, so this is creating a new string each time you add to it. If you have never used StringBuilder, look it up. It is very useful for this sort of work.

    2) You can make your method easier to reuse if you pass the length into the method itself. You could probably pass the chars array in as well, but I've left that out.

    3) Use the same random object each time, as suggested above.

    public string GenerateRandomString(int length)
    {
        StringBuilder randomString = new StringBuilder(length);
    
        for (int i = 0; i < length; i++)
            randomString.Append(chars[(int)(_RandomObj.Next(chars.Length))].ToString());
    
         return randomString.ToString();
    }
    

提交回复
热议问题