Reputation: 127
I'm trying to make a Rock Paper Scissors game as my first 'project' so I need the computer to generate a random number from 1-3 to represent their turn.
I've been trying this code but I can't figure out why it's not working:
Random rnd = new Random();
int pchand= rnd.Next(1, 4);
There's a red squiggly line below rnd that says :
A field initializer cannot reference the non-static field, method, or property FileName.Form1.rnd
Thanks for any help!
Upvotes: 0
Views: 165
Reputation: 48415
The problem will be because you are doing this at a class level, rather than a function level.
It is fine to declare you Random at class level, but creating pchand
should be done within a function.
Something like:
public class Test
{
static Random rnd = new Random();
public static void Main()
{
int pchand = rnd.Next(1, 4);
}
}
The reason why your original attempt causes a compile time error is because the compiler does not guarantee the order in which fields are initialized. So there is no guarantee that rnd
will be set before you use it. Thus the compiler prevents you from doing it to avoid unexpected null reference errors during runtime.
Note to OP: Including a more extended sample of your code would have allowed for a more specific solution to your problem, but hopefully my example code is generic enough for you to understand what you need to do
Upvotes: 10