Lesson 11.1 – Using a static class

Lesson Objectives

At the end of this lesson, you will know…

  • What a static class is, and how to create one.
  • When you want, and don’t want, to use static classes


What is a static class?

All the classes we’ve created so far have been public classes. That means they are visible in all of your program. However, in order to use one of them, you need to create an object of the class. Then you work with that object.

A static class is one that is always available to the rest of your program – you don’t need to create an object from it. In fact, you can’t create an object from a static class. It’s just there.

A static class is a place to hold shared resources (variables and methods), since there will only be the one “instance” of it, and everything else in your program will use that one, shared set of methods and variables.

Why would you need a static class?

For our game, we need to store some things that will be used in several places in the program.

Things like the list of locations, the types of items, the types of monsters, etc. This information is never going to change. We’re going to populate these lists at the start of the game, and never change it. We’re also going to use those lists in several places in the game.

Using a static class to hold all this information is one way to make all this information available everywhere.

When else would you use a static class?

Another thing you can do with a static class (and a static variable) is to hold values such as a system-wide counter.

Let’s say you want a program to hand out unique, sequential numbers to the people who use it.

You could create a static NumberAssigner class, with a static GetNextNumber method, that keeps track of a static _nextNumber variable.

When you start the program, _nextNumber has a value of 0.

When a user calls the GetNextNumber method, the code adds 1 to _nextNumber and returns the value (in this case, 1) to the program. The next time the GetNextNumber method is called, it adds 1 to _nextNumber (resulting in 2 this time) and returns 2 to the program.

What problems can happen with static classes?

The problem with static methods and variables, is that sometimes you don’t want a shared resource, you want each user to have their own copy of the object or variable.

The game we’re creating is a single-player one. So, we don’t really have a problem using static variables.

However, if we were to make a UI for this game a website on the Internet, we might have several people playing it at the same time.

So, let’s say we stored the player’s current hit points somewhere as a static variable – CurrentHitPoints.

When player A is attacked, the program would subtract their damage and change the value of CurrentHitPoints. But if a different player did something in the game (attacked a monster or healed themselves with a potion), since we only have a static, single, shared CurrentHitPoints variable, they’d be using the value from player A, and not their real current hit points value.

That’s how static classes and variables can be dangerous. When you use a static variable to hold a value, make sure it’s one that you really want to be shared for every user.


Populating our game world in a static class

Now that you have an understanding of static classes and variables, we’re going to create a “World” class to hold lists of all the things in our game – locations, items, monsters, and quests.

Since we’re only going to read from it, once we do the initial population of the values, it’s OK to use a static class.

Step 1: Start Visual Studio Express 2013 for Desktop, and open the solution.

Step 2: Create a new class by right-clicking on the Engine project and selecting “Add”, then “Class…”. Name the class “World.cs”

Step 3: Copy the code for the class from here: https://gist.github.com/ScottLilly/803df1021fbc404b38f5


What does the code do?

The purpose of the World class is to have one place to hold everything that exists in the game world. In it, we’ll have things such as the monster that exist at a location, the loot items you can collect after defeating a monster, etc. It will also show how the locations connect with each other, building our game map.


Here is what is happening in the different parts of the World class.

Lines 11 – 14: Static list variables. These work similar to the properties in a class. We’ll populate them with all the things in our game world, then read from them in the rest of the program.

Line 16 – 42: Constants. Constants look, and work, like variables, except for one big difference – they can never have their values changed.

We’re going to use these constants, which have a sort-of English name, so we don’t have to remember the numeric ID for each of the different games objects. Without them, if we wanted to create a giant spider for the player to fight, we’d need to remember that the giant spider monster has an ID value of 2. With the constants, we can say, get me a monster where the ID equals MONSTER_ID_GIANT_SPIDER.

If you don’t fully understand how we’ll do that, it should become clearer when we get to the lesson where we start having the player move around and we need to lookup locations, quests, monsters, and items.

Lines 44 – 50: This is the static constructor. You might be thinking, “Wait! We can’t instantiate a static class, so why does it have a constructor? After all, that’s what a constructor is used for – instantiating an object!”

With a static class, the constructor code is run the first time someone uses anything in the class. So, when we start the game and want to display information about the player’s current location, and we try to get that data from the World class, the constructor method will be run, and the lists will get populated.

Inside the constructor, we call the four methods to populate the different lists. We don’t need to have separate methods, and we could have put all the code from lines 48 through 169 into the constructor. But breaking them up makes them easier to read and work with.

Lines 52 – 173: These are the methods we use to create the game objects and add them to the static lists.

By calling the Add() method on a list variable or property, we add an object to that list.

Look at line 54. Here we are adding a new Weapon object to the Items list. When we call “new Weapon()”, the constructor of the Weapon class returns a Weapon object with the parameters passed in. Since that’s all inside “Items.Add()”, that object gets added to the Items list.

You might hear that called “inlining”, since we did multiple things (created the value and added it to the list), all in one line.

On line 68, we create a new Monster object and save it to the variable “rat”. On lines 69 and 70, we add items to the (list) property of PotentialLootItems that you might find on the rat. Then, on line 80, we add the rat variable to the static Monsters list.

Lines 175 – 225: These methods are ones we can call to get values from the static lists. We could access the lists from lines 7 through 10 directly, since they are public. But these “wrapper” methods make it a little clearer exactly what we want to do.

We pass in the ID of the object we want to retrieve from its list (by using the constants from lines 16 through 42). The method will look at each item in the list (using the “foreach”) and see if the ID we passed in matches the ID of the object. If so, it returns that object to us. If we get to the end of the list, and nothing matches (which should really never happen), the method returns “null” – nothing.



Now we have a populated “world” for the game. We can use the static methods from this static class at any place in the rest of our program, and get the information we need about the objects in our game world.


Click to view source code



Source code for this lesson

Get it from GitHub: https://gist.github.com/ScottLilly/803df1021fbc404b38f5

or DropBox:  Lesson 11.1 – https://www.dropbox.com/sh/tj2ur83gnjxd7k0/AADyad0df8n797nQkJ4Yky8Na?dl=0


Next Lesson: Lesson 12.1 – Add the remaining UI controls

Previous lesson: Lesson 10.1 – Creating collections of objects

All lessons: Learn C# by Building a Simple RPG Index


88 thoughts on “Lesson 11.1 – Using a static class

  1. Hey, I seem to be having problems with anything that uses “ItemByID”. For example…

    rat.LootTable.Add(new LootItem(ItemByID(ITEM_ID_RAT_TAIL), 75, false));

    …ItemByID will always be marked as an error, saying that “the item ‘ItemByID’ does not exist in the current context.” I’ve gone over all my previous code, and checked it against yours, but from what I’ve seen, everything looks fine.

    What could my issue be?

  2. Nevermind! All this time, I thought I had made a mistake somewhere in the previously written code, when all I was doing was getting ahead of myself.

    Oh well. All that searching and digging helped me learn a bit. I’ll chalk that up as win for me.

    Merry belated Christmas, and thanks for the tutorial. 😀

  3. Hi Scott,

    Great tutorial, much appreciated!

    Could you tell me we are setting quests in a given location below the constructor instead inside of it?

    Thank you.

    1. You’re welcome

      All locations do not have a quest. So, I did not put a Quest parameter in the Location constructor. You could add a Quest parameter, and pass in “null”, or make it an optional parameter. But for this code, I chose to add the quest this way – just my preference for here. The other ways would work just as well.

  4. Hi Scott!

    Great tutorials.


    I was a bit lazy in the end and copied alot, got some errors which i solved.

    Although i still got 2 more errors in the World.cs on line 88 and 98 “Quest clearAlchemistGarden =
    new Quest(
    “Clear the alchemist’s garden”,
    “Kill rats in the alchemist’s garden and bring back 3 rat tails. You will receive a healing potion and 10 gold pieces.”, 20, 10);


    Line 98 is the same error, so there is only one thing to fix, although i cant figure it out.


    The error message is “There is no argument given that corresponds to the required formal parameter ‘rewardItem’ of ‘Quest.Quest(int,string,string,int,int,Item)’


    Any help would be appreciated.


    Sincerely/ Johan

    1. Thank you, Johan!

      That error message shows the Quest constructor expects six parameters – the “int, string, string, int, int, Item”. And, the line calling the constructor only has five parameters. Make sure your Quest class matches the one from lesson 10.1 (which you can also see here: Quest.cs).

      Please tell me if that does not fix the error.

  5. Hi Scott!

    I manage to solve it, where i added the 6th parameter, it tooked a while but now it’s working.
    I tested the code and found that the it’s not possible to use the weapon, will continue the troubleshooting.

    It was relatively easy until the copy/paste of world.cs, lot’s of code there and lots of errors since i couldn’t find all the information/code needed in the videos.

    I’m improving my troubleshooting skills though.

    Thanks for the quick reply

    Sincerely/ Johan

  6. Your Location objects don’t have any methods/properties which allow linking the locations together. ie. home.LocationToNorth. Each of these entries throw an error, which is what he might be talking about.

    1. Hi Josh,

      I’m sorry it took a while to respond – I’ve been on vacation.

      Are you seeing errors on the lines where we set the LocationToNorth (etc.) properties? If so, please let me know what the complete error messages says?

      The previous commenter had some other problems (I think it was in the solution files) that were causing their errors.

    2. I was also having this problem, but I have been naming things differently (on purpose so I can see how the errors effect other parts (I find it easier to learn from errors)) So if I had to guess, it is a naming problem.

      1. If you are seeing the error message “Cannot implicitly convert Engine.Item to Int”, check the datatype of the RewardItem property in the Quest class – to make sure it is “Item”, and not “int”.

        If you are getting other error messages, and you cannot fix them, please let me know what they are.

  7. clearAlchemistGarden.RewardItem = ItemByID(ITEM_ID_HEALING_POTION);
    clearFarmersField.RewardItem = ItemByID(ITEM_ID_ADVENTURER_PASS);
    –> “Cannot implicitly convert Engine.Item to Int”

    Is this normal? I used Visual Studio 2017

    Needed to change that to:
    clearAlchemistGarden.RewardItem = Convert.ToInt32(ItemByID(ITEM_ID_HEALING_POTION));
    clearFarmersField.RewardItem = Convert.ToInt32(ItemByID(ITEM_ID_ADVENTURER_PASS));

    1. Hi Jonny,

      I’m sorry I couldn’t answer sooner. I just got back from vacation.

      Check your Quest class, and make sure the datatype for the RewardItem property is “Item”, and not “int”. That property should look like this:

      public Item RewardItem { get; set; }

      Please let me know if that doesn’t fix the errors.

      1. Hi Scott Lilly,
        I’m sorry for my delayed answer, I’ve had a lot to work on this past 6 weeks or so.

        But nevermind that; yes, that unfortunate typo was the problem, I don’t know why I didn’t spot that earlier.

        Thanks for the help.

  8. Hi Scott,

    I get about nine erros in my World, Player and Monster class all stating the following:
    Error 1 Inconsistent accessibility: field type ‘System.Collections.Generic.List’ is less accessible than field ‘Engine.World.Items’

    What am I doing wrong?

    1. Check the World, Player, and Monster classes. Make sure the classes are declared as “public” (for example, Player.cs should have “public class Player”). Also, check the properties in those classes, (and probably Location, Item, etc.), to make sure they are declared as public, and their properties are public.

      If you still have errors after checking those, please tell me here.

Leave a Reply

Your email address will not be published. Required fields are marked *