Correct method of a “static” Random.Next in C#?

前端 未结 11 2211
执念已碎
执念已碎 2020-12-10 10:51

Why do i need to create an instance of Random class, if i want to create a random number between 1 and 100 ....like

Random rand = new Random();
rand.Next(1,1         


        
11条回答
  •  無奈伤痛
    2020-12-10 11:09

    It's not "unnecessary", because the Random class stores some state internally. It does that to make sure that if you call .Next() multiple times very quickly (in the same millisecond or tick or whatever) you still won't get the same number.

    Of course, if that's not a problem in your case you can always combine those two lines of code into one:

    new Random().Next(1, 100);
    

提交回复
热议问题