Kestis
Kestis

Reputation: 163

Can't generate random number

I'm trying to generate random numbers in a loop. I make an instance of the Random class before the loop starts, but it is inaccessible. The error i get is:

'System.Random.Sample()' is inaccessible due to its protection level

My code is:

Random random = new Random();
   while (ready == false)
   {
       double h = random.Sample();
   //Lots of things done here
   }

What's wrong?

Upvotes: 1

Views: 471

Answers (3)

Jobs
Jobs

Reputation: 3377

To use the protected Sample method, you need to "derive a class from the Random class and override the Sample method", according to the documentation.

What you need is NextDouble(), which returns a random floating-point number that is greater than or equal to 0.0, and less than 1.0.

Please see the documentation below:

http://msdn.microsoft.com/en-us/library/system.random%28v=vs.110%29.aspx

Use

double h = random.NextDouble();

Instead.

Upvotes: 1

Heinzi
Heinzi

Reputation: 172200

The documentation of the Sample method explains this behaviour:

Important

The Sample method is protected, which means that it is accessible only within the Random class and its derived classes. To generate a random number between 0 and 1 from a Random instance, call the NextDouble method.

The purpose of the Sample method is to override it if you want to create your own, custom random number generator. If you just want to use the Random class, NextDouble is the correct method to call.

Upvotes: 8

Selman Genç
Selman Genç

Reputation: 101680

You need to use NextDouble method.

 double h = random.NextDouble();

The method you are trying to call is not public as stated in the error message.

Upvotes: 5

Related Questions