Sunil Sunil -4 years ago 112
C# Question

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

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,100);


Is there any static function of Random class to do the same? like...

Random.Next(1,100);


I don't want to create an instance unnecessarily

Answer Source

It is best practice to create a single instance of Random and use it throughout your program - otherwise the results may not be as random. This behavior is encouraged by not creating a static function.

You shouldn't worry about "creating an instance unnecessarily", the impact is negligible at best - this is the way the framework works.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download