1

A followup to this post: Need advice on design/structure of a game

I have Game.cs, which essentially holds my gamestate. All necessary variables will be included here when everything is said and done to make saving, loading, and starting a new game easier. My question is this: Should this class be static or dynamic? I tried dynamic, but I can't figure out where to instantiate it properly. At the moment, Game.cs is instantiated when a button click event fires in a Windows Form, but afterward is treated as a local variable and it can't be accessed elsewhere. Is there a way to instantiate it globally? Or in this case is static the way to go?

Community
  • 1
  • 1
Jason D
  • 2,634
  • 6
  • 33
  • 67
  • 4
    BTW, `dynamic` isn't really the word you are looking for. A `Dynamic` object is one whose variables and methods are established at runtime, not compile time. Also see: http://stackoverflow.com/questions/241339/when-to-use-static-classes-in-c-sharp – NotMe May 14 '13 at 22:08

2 Answers2

4

Have the Game class be an instance class: everything should be instance fields/properties/methods, not static.

Within your game, you should have just one instance of the Game class. You could pass it around to all of the other classes, or you could just make it global, by making it a public static public field on some class.

David Yaw
  • 27,383
  • 4
  • 60
  • 93
3

As a rule of thumb, static classes/methods should be stateless. If you want to have your data accessible from anywhere, you should go for the Singleton-Pattern.

public class Game
{
    private static Game instance;
    public static Game Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Game();
            }
            return instance;
        }
    }

    private Game()
    {
    }

    private int someData;

    public string SomeMethod()
    {
    }

    // ...
}

Then, access it in your code like so:

string myString = Game.Instance.SomeMethod();
Jan Dörrenhaus
  • 6,581
  • 2
  • 34
  • 45