Reputation: 1152
I'm sure this question is asked a lot but I cannot find an answer anywhere that helps me. I'm trying to create a random double between 0 and 1, and I keep getting errors.
map[x,y].setBit((int) Math.Round(((((double)Random.Next(100))/100) * 1.3), 2);
the error I get says "An object reference is required for the non-static, method, or property "System.Random.Next(int)"
Upvotes: 1
Views: 1891
Reputation: 300797
Random is a class. Random.Next() is a non-static method.
Therefore you need to instantiate an instance of the Random
class. (Note: as Spender pointed out, don't make this local to a loop...)
Random rnd = new Random();
map[x,y].setBit((int) Math.Round(((((double)rnd.Next(100))/100) * 1.3), 2);
Upvotes: 3
Reputation: 126982
The error message tells you precisely the problem. Random
is a class. Next
is a non-static method. You need an instance, or object reference, of the class in order to use that method.
var random = new Random();
// use random.Next(upperLimit);
You should note that if you are using random
in a tight loop, you would want to create the instance outside the loop and reuse it, or at an otherwise higher level (such as a member field of a class). The way the class is seeded, successive instances will generate the same "random" sequences of values. This is a common pit that people have fallen into.
You should also be aware that based upon your usage where you are getting an integer from 0 to 99, casting to double, and dividing by 100... there's a more straightforward approach. Simply use NextDouble()
, which gives a value greater than or equal to 0 and less than 1.0.
double d = random.NextDouble();
Upvotes: 8