Jason D
Jason D

Reputation: 2664

Static or dynamic class?

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?

Upvotes: 1

Views: 638

Answers (2)

David Yaw
David Yaw

Reputation: 27874

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.

Upvotes: 4

Jan Dörrenhaus
Jan Dörrenhaus

Reputation: 6717

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();

Upvotes: 3

Related Questions