-2

I apologise, I know this question has been asked a thousand times before by C# beginners (of which I am one), but all the answers I can find say I need to either instantiate the class, or make it static. My class is instantiated, and I am trying to access the instance. Can anyone take a look at my code and work out what is going wrong?

public class RocketSimMain {

    public RocketShip test = new RocketShip ();

    public static void Main() {

        ... // Do some setup stuff here

        //Run the game loop
        while (!EndGameRequested()) {
            test.Move();  <- Object instance error here.
        }
    }
}

As you can see, I'm instantiating the class and accessing the instance. The only thing that works is instantiating the class inside the Main method, but then I'm not able to access it in other classes.

Daniel Forsyth
  • 313
  • 2
  • 4
  • 15

2 Answers2

0

You have to make test static in order to use it from a static method (Main).

Tamás Zahola
  • 9,271
  • 4
  • 34
  • 46
-1

This problem arises because you are trying to call a non-static class from a static method.

To solve it you must either make them both non-static:

public RocketShip test = new RocketShip ();

public void Main() 
    {

    ... // Do some setup stuff here

    //Run the game loop
    while (!EndGameRequested()) 
    {
        test.Move();  <- Object instance error here.
    }

or instantiate it locally within the method:

public static void Main() 
{
     RocketShip test = new RocketShip ();

    ... // Do some setup stuff here

    //Run the game loop
    while (!EndGameRequested()) 
    {
        test.Move();  <- Object instance error here.
    }
}
JBrennan
  • 1
  • 1
  • 1