Lesson 05.1 – Creating objects from classes

Lesson Objectives

At the end of this lesson, you will know…

  • How your program can create objects (instantiation)
  • How to assign values to an object’s properties
  • How to use (reference) classes in different projects
  • How to display the values from an object’s properties on the UI


Instantiating your first object

Now that we have the Player class created, we can create an “instance” of the class – a Player object. This is how we go from just having the outline (the class) to having a Player (object) that the game can use.


Link to video on YouTube


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

Before we do anything else, let’s remove the test button we added in the previous lesson.

In the SuperAdventure UI project, double-click on SuperAdventure.cs to see the form.

Click on the “Test” button once, to select it. You’ll see that it has dashes around it. Press the “Delete” key to remove it.

Right-click on SuperAdventure.cs, in the Solution Explorer, and select “View Code”, to see the code for this form. Delete lines 19 through 23.

Now we are ready to create our Player variable.


Step 2: We’re going to use this one Player object in several places in the SuperAdventure screen. So, we need a place to store it. That’s exactly what a variable does – stores a value so we can retrieve it later.

In this case, we need to create a “class-level” variable. That means it can be seen by everything in the class.

You create a class level variable by having it inside your class (in this case, the SuperAdventure form – which is a class), but outside of any functions or methods.

Go to the end of line 14 and press the enter key, to create a new line.

Type this on line 15:

private Player _player;

So now, the code for your class will look like this:

    public partial class SuperAdventure : Form
        private Player _player;

        public SuperAdventure()

Just like with the properties we created for the Player class, the variable has three parts:

First is the scope. The scope here is “private”, since we don’t need anything outside of this screen to use the variable.

The datatype is “Player”, because we want to store a Player object in it.

And the name is “_player”. You could name it anything, and it doesn’t need to start with an underscore. That’s just how I like to name my private variables.

Notice that Player has a red squiggly line under it. That means there is a problem. In this case, it’s because the SuperAdventure form doesn’t know where the Player class is located.


Step 3: Go to line 10, press the enter key, then type in this line:

using Engine;

The beginning of the class will look like this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using Engine;

The red line disappears, because the SuperAdventure form knows to find the Player class in the Engine project. You need to do this for each class, when it uses classes from a different projects.

NOTE: If the red line does not disappear, please check the comments section below. There are solutions for the most common causes of that problem.

Now we have a place to store the Player object, although we haven’t created one yet.


Step 4: There is some code that starts on line 19. This is called the “constructor” for the class (the form, like everything in .Net, is a class). The code in the constructor gets called when we create a new object of the class – in this case, the form.

This is where we’ll instantiate a Player object and store it in the _player variable.

Go to the end of line 21 and press the enter key twice. (You don’t really need to do it twice, but it’s nice to have some blank space in your code).

On line 23, type in this line:

_player = new Player();

This creates a new Player object (that’s what is happening on the right side of the equal sign). Then it assigns that object to the _player variable that we created on line 17.

Now that we have a Player object, we can start working with it – setting its properties and reading them.

NOTE: When you see a single equal sign in C#, it’s for assignment – it’s assigning the result of whatever happens on the right side of the equal sign to the property or variable on the left side. We’ll get to what you use to compare if two values are equal to each other later on.


Step 5: Add a blank line on line 24, then add these lines after it:

_player.CurrentHitPoints = 10;
_player.MaximumHitPoints = 10;
_player.Gold = 20;
_player.ExperiencePoints = 0;
_player.Level = 1;

Your constructor will look like this:

        public SuperAdventure()

            _player = new Player();

            _player.CurrentHitPoints = 10;
            _player.MaximumHitPoints = 10;
            _player.Gold = 20;
            _player.ExperiencePoints = 0;
            _player.Level = 1;

On these lines, we’re assigning values to the properties of the _player object.


Step 6: Add a blank line on line 30, then add these lines after it:

lblHitPoints.Text = _player.CurrentHitPoints.ToString();
lblGold.Text = _player.Gold.ToString();
lblExperience.Text = _player.ExperiencePoints.ToString();
lblLevel.Text = _player.Level.ToString();

Now, you should have this:

        public SuperAdventure()

            _player = new Player();

            _player.CurrentHitPoints = 10;
            _player.MaximumHitPoints = 10;
            _player.Gold = 20;
            _player.ExperiencePoints = 0;
            _player.Level = 1;

            lblHitPoints.Text = _player.CurrentHitPoints.ToString();
            lblGold.Text = _player.Gold.ToString();
            lblExperience.Text = _player.ExperiencePoints.ToString();
            lblLevel.Text = _player.Level.ToString();

In these lines, we’re getting the values of the properties from the _player object, and assigning them to the text of the labels on the screen.

Remember how I mentioned earlier that you cannot assign an integer value to a string, or vice versa?

Since the Text property is a string, and the CurrentHitPoints, Gold, ExperiencePoints, and Level properties are all integers, we need to add the “ToString()” at the end of them. This is a common way to convert numbers to strings.

Step 7: Save the code and Start the program. Now you should see the values we assigned to the _player properties showing up on the screen. If you want to, you can stop the program, change the values in lines 25 through 29, re-start the program, and see how they change.



Now you can create a variable, instantiate an object from a class in a different project, assign the object to the variable, change the values on the object’s properties, and display the changes on the UI.

That’s a huge part of the foundation of writing programs in any object-oriented language.


Source code for this lesson

Source code on GitHub

Source code on DropBox


Next Lesson: Lesson 06.1 – Creating the remaining classes

Previous lesson: Lesson 04.1 – Creating the Player class and its properties

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

132 thoughts on “Lesson 05.1 – Creating objects from classes

  1. Im getting errors every time I run the program since this lesson, can you help me?
    This is the error list:

    2 of these CS0246
    8 of these CS1061

    what is happening and what can I do to fix it?

  2. I’m also getting a single cs 1061 error.

    This code: “this.Load += new System.EventHandler(this.SuperAdventure_Load);” was throwing up the error – I removed it and it seemed to fix itself…

    1. Hi Sam,

      That might have happened if you accidentally double-clicked on the SuperAdventure form, while you were in the Design screen. Visual Studio “helps” you by creating an eventhandler and a function in SuperAdventure.cs. Then, if you paste in code from the lesson, it doesn’t have the function it created – which is what the error message is trying to say. Deleting it is the correct thing to do.

      You can find out more about eventhandlers in Lesson 21.3.

    1. Check to ensure you added a “reference” to the Engine project, inside the UI project. It’s step 6 of Lesson 02.2.

      That might also happen if you gave the project a different name. To fix that, look at Lesson 02.2B.

      Please tell me if those do not fix the problem.

  3. Hi Scott,

    Thanks for this great tutorial! Unfortunately, I’m running into a weird problem. None of the code seems to be out of place (no red squiggly lines anywhere), but I get these messages when I try to test it:

    1>—— Build started: Project: MTEngine, Configuration: Debug Any CPU ——
    1>C:\Users\Gebruiker\source\repos\MiningTown\MTEngine\Class2.cs(9,18,9,23): error CS0101: The namespace ‘MTEngine’ already contains a definition for ‘Miner’
    -*MTEngine is my ‘Engine’ class library, and instead of ‘Player’ I use ‘Miner’.
    Essentially, the message should be the opposite of a problem.

    2>—— Build started: Project: MiningTown, Configuration: Debug Any CPU ——
    2>C:\Users\Gebruiker\source\repos\MiningTown\MiningTown\MiningTown.cs(18,17,18,22): error CS0246: The type or namespace name ‘Miner’ could not be found (are you missing a using directive or an assembly reference?)

    I added a reference to MTEngine, so I don’t see how this message could crop up.

    Do you have any idea how to fix this?

      1. Thanks for getting back to me so quickly! I already figured it out. It was quite a silly mistake. I made one class which I called ‘Miner’, then used another (Class2) to define ‘Miner’ as a class. I should have listened to you when you told us to delete Class1!

  4. Just wanted to say how amazing of a tutorial this is and that everything is still working as it should. Such a great learning experience, thanks for all the time and effort you put into it!

  5. HI Scott, I have all these _Click files that i do not seem to understand in my code. I am using visual studio 2019.

    1. If you accidentally double-clicked on the screen when it’s in design mode (the graphic version of SuperAdventure class), Visual Studio will create a function (usually with “_Click” in its name) and an eventhandler. If you delete the functions, you will also need to delete the eventhandler that links to the function – it will be in SuperAdventure.Designer.cs.

      You can read more about eventhandlers in lesson 21.3.

      Let me know if you have any questions after looking at lesson 21.3, or if you have any problems running your program. I can help you fix your program, if you need.

  6. Engine still has red squiggly lines after i referenced and wrote the correct namespace.

    I think it has something to do with my visual studio version.

    Do you have any idea why? and how to fix it?

  7. Would it work if I wrote Player _player = new Player(); instead of what you wrote? If not, what is the difference between them?

    1. Yes, that would work – for a short time.

      Your change would create a new player object when the class is instantiated. Then, when the constructor is run and gets to line 23, it would instantiate another Player object and put that new object into the variable – overwriting the one that was created by your change to line 15.

  8. kind sir, When i use the LBL part it keep having the CS 1519 and IDE1007 even tho I already have the same class

  9. Nothing is working I just keep getting “The type or namespace ‘Player’ could not be found.” All I did was follow everything as you did!

  10. This is such a fantastic tutorial! Scott has taken the time to teach programming in a very fun way. I am also a software engineer and just love going though tutorials like this… You know, for fun, cause, let’s face it, we are all geeks and nerds.
    Scott mentioned that he will not be going into detail on very advanced topics, But I’d like to add a little something, if I may. In programming there are many roads to get you where you want to go. Some of those roads are smooth, others are rocky.
    In the case of this chapter, instantiating a class/creating an object can be completed a few different ways. These all do the same thing.
    var player = new Player();
    player.CurrentHitPoints = 10;
    player.MaxHitPoints = 10;
    player.Gold = 20;
    player.ExpPoints = 0;
    player.Level = 1;

    The second way is to use an object initializer
    var player = new Player
    CurrentHitPoints = 10,
    MaxHitPoints = 10,
    Gold = 20,
    ExpPoints = 0,
    Level = 1

    A Third way, and probably the best way, is to use a constructor. Scott discusses this in Chapter 8.1
    var player = new Player(10, 10, 20, 0, 1);

    Note: To do this, you will need to add the method into the Player class. Below is an example of the constructor. Quick Hint, Constructor methods have the same name as the Class they are in 🙂
    public Player(int currentHitPoints, int maxHitPoints, int gold, int expPoints, int level)
    CurrentHitPoints = currentHitPoints;
    MaxHitPoints = maxHitPoints;
    Gold = gold;
    ExpPoints = expPoints;
    Level = level;

Leave a Reply

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