Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

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

I have a simple piece of code:

public string GenerateRandomString()
        {
            string randomString = string.Empty;
            Random r = new Random();
            for (int i = 0; i < length; i++)
                randomString += chars[r.Next(chars.Length)];

            return randomString;
        }

If i call this function to generate two strings, one after another, they are identical... but if i debug through the two lines where the strings are generated - the results are different. does anyone know why is it happening?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is happening, because the calls happen very close to each other (during the same milli-second), then the Random constructor will seed the Random object with the same value (it uses date & time by default).

So, there are two solutions, actually.

1. Provide your own seed value, that would be unique each time you construct the Random object.

2. Always use the same Random object - only construct it once.

Personally, I would use the second approach. It can be done by making the Random object static, or making it a member of the class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...