1

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)"

Glen654
  • 1,102
  • 3
  • 14
  • 18

2 Answers2

8

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();
Community
  • 1
  • 1
Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
  • Thanks! For some reason when I googled that error, I never got that solution... I'm a bit new to this language, as you can probably tell ^.^ – Glen654 Mar 30 '12 at 02:48
  • 1
    You will be pleased to note that this very question is already 4th on [google](https://www.google.com/#hl=en&output=search&sclient=psy-ab&q=An+object+reference+is+required+for+the+non-static%2C+method%2C+or+property+%22System.Random.Next(int)&oq=An+object+reference+is+required+for+the+non-static%2C+method%2C+or+property+%22System.Random.Next(int)&aq=f&aqi=&aql=&gs_l=hp.3...553l5395l0l5883l3l3l0l0l0l0l166l380l1j2l3l0.frgbld.&pbx=1&bav=on.2,or.r_gc.r_pw.r_qf.,cf.osb&fp=8eaf7f526a5ea16c&biw=1440&bih=815) for that precise message. ;) – Anthony Pegram Mar 30 '12 at 03:00
3

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); 
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
  • Seeing as this looks like it's being done in a loop (possibly even nested loops), those 2 lines look dangerously close together. Worth mentioning that `rnd` should most likely not be local. – spender Mar 30 '12 at 02:46