Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

random

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

like image 504
Sunil Avatar asked Apr 15 '10 07:04

Sunil


People also ask

What is next () in C#?

Next() method in C# is used to return a non-negative random integer.

What does random next return?

Next() Returns a non-negative random integer.

Is there a random function in C#?

The Random class in C# provides defined methods that generate random integers. The most widely used method to generate random integers from the Random class is Next() . The Random.

How do you do random in C sharp?

To generate random numbers in C#, use the Next(minValue, MaxValue) method. The parameters are used to set the minimum and maximum values. Next(100,200); We have set the above method under Random() object.


1 Answers

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.

like image 57
Kobi Avatar answered Oct 14 '22 23:10

Kobi