Singleton pattern in .net and c#

I was talking to my brother earlier (also a developer, although specializing in game development) and he mentioned that he’s always had an issue implementing the singleton pattern under c#/.net, also citing that he finds it a bit tricky generally when using OO languages.

Well, here’s one way to do it. As he’s a game developer, let’s assume that we’re using the pattern to accomodate the current state of a video game.

    

class GameState
    {
        //The Single Instance
        private static GameState _singleton = new GameState();     

        //The constructor
        private GameState()
        {
            _score = 0;
        }

        //A "player score" property and member
        private int _score;
        public static int Score
        {
            get
            {
                return _singleton._score;
            }
            set
            {
                _singleton._score = value;
            }
        }
    }

Possible improvements to this would be to have a static “initializeGameState()” method and create the singleton instance in there instead. Either way, using the above method allows you to write code like this;

           
GameState.Score = GameState.Score+100;

I don’t find much use for the singleton pattern in my line of work (the web) but hopefully this’ll be of use to someone!

EDIT: Many good improvements have been suggested in the comments which can help to make this even lazier (in my example, the initialization of the singleton would happen the first time someone used any of the static methods in the code, rather than when the user perhaps intended to start)

Advertisements

8 thoughts on “Singleton pattern in .net and c#

  1. Also, singletons can be useful in cases of “manager” objects, emenymanager, input manager etc. Alxader’s suggestion is also a bit clearer in my opinion.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s