0

I'm new to coding Blah Blah same old story but I put this code in:

{
    public static Random Random;

    public int numberOne = 5;
    public int numberTwo = 6;


    public void Run()
    {
        numberOne = Random.Next(0,11);
        numberTwo = Random.Next(0,6);

        Console.WriteLine(numberOne +" + "+ numberTwo);
        Console.ReadKey(true);
    }

numberOne and numberTwo are both public int's. Why doesnt this work?

it comes back with an error stating that

"System.NullReferenceException: Object reference not set to an instance of an object."

What does that mean?

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
deviousPriest
  • 13
  • 1
  • 5

1 Answers1

1

Let's use my crystal ball: in the code in the question - since numberOne and numberTwo are int - the main possibility to have

System.NullReferenceException: Object reference not set to an instance of an object

is the fragment like this:

// just a declaration without initialization
public static Random Random; // <- the instance doesn't created

...

{
// Addressing Random which is null cause NullReferenceException 
numberOne = Random.Next(0,11);
numberTwo = Random.Next(0,6);

Console.WriteLine(numberOne +" + "+ numberTwo);
Console.ReadKey(true);
}

Remedy: initialize the field with created Random instance

// Now Random is initialized
private static Random Random = new Random();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215