Press "Enter" to skip to content

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()
        {
            InitializeComponent();
        }
    }

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

            _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()
        {
            InitializeComponent();

            _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.

 

Summary

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

171 Comments

    • Scott Lilly
      Scott Lilly November 3, 2024

      Hello,

      I’m sorry it took me a couple days to answer. There were a few problems. Since you’re at the beginning, it might be easier to start over, but you can try doing these things to fix the current project. See the screenshot below.

      1. Delete/remove the SuperAdventure.cs file in the Engine project
      2. Right-click on “References” in the SuperAdventure project, select “Add Reference…”, select “Projects”, check the checkbox next to “Engine”, and click the “OK” button
      3. Click the triangle next to SuperAdventure.cs in the SuperAdventure project, so you can see “SuperAdventure.Designer.cs”
      4. Double-click on SuperAdventure.Desinger.cs
      5. Delete the four lines that have “.Click += new System.EventHandler”. Those are trying to connect things in the UI to code in SuperAdventure.cs, but that code is not there yet. Right now, that is on lines 51, 87, 124, and 134.

      Please let me know if that does not fix the errors.

  1. Jean-Laurier Lafrance
    Jean-Laurier Lafrance December 31, 2024

    Hi Scott! First i want to say thank you so much for this wonderful tutorial.
    Ive been trying to troubleshoot this by myself for a few hours now without success.
    The type or namespace name ‘Player’ could not be found (are you missing a using directive or an assembly reference?)
    I made sure the engine was referenced, my class is public i cleaned and rebuilt the solution but nothing is doing it. Maybe you can help?

    • Scott Lilly
      Scott Lilly January 1, 2025

      Hello! You’re welcome.

      Can you please upload your solution (including the directories under it, and all the files in those directories) to GitHub, Dropbox, or some other file-sharing location so I can look at it?

      If you haven’t used GitHub before, here is a video on how to upload your solution to GitHub and share it with me. https://youtu.be/0si9ElYQv8I

        • Scott Lilly
          Scott Lilly January 2, 2025

          It looks like the Engine project is set up as a VB.NET Class Library project, but needs to be a C# Class Library project. You can see this if you look as the files in Windows Explorer. Under the SuperAdventure folder, there is SuperAdventure.csproj. The “csproj” is for C# projects. Under the “Engine” folder, there is “Engine.vbproj”. The “vbproj” is for projects that are written with VB.NET.

          To fix this, the easiest solution is probably to:
          1. Close Visual Studio
          2. Delete the “Engine” directory (and all the files under it)
          3. Open the solution in Visual Studio (ignore the error message)
          4. In Solution Explorer, right-click on the “Engine (not found)” project and choose “Remove”
          5. Recreate the “Engine” project as a C# Class Library (following most of the steps from lesson 2.2 to the current lesson)

          Please let me know if that is not clear, or if that has any problems.

  2. ping an
    ping an January 3, 2025

    Hello, I have a problem after finishing the fifth class, the program cannot run after finishing all steps, I uploaded my project, please help me to find out what my problem is, in addition, please ignore the uploaded one named “WindowsFormsApplication1”, because I do not know how to delete it.My English is not very good, please forgive me.
    https://github.com/PingAn-Chen1/My-Problem/tree/master

    • Scott Lilly
      Scott Lilly January 3, 2025

      Hello Ping An,

      I think I found the problem. If you accidentally double-click on the Windows Form, it creates a “Load” eventhandler and function. If you copy the code from the lesson, it does not have the function, but the eventhandler is still in the code. You can learn more about eventhandlers in lesson 21.3

      To fix this, edit the SuperAdventure.Designer.cs file (see the screenshot below and click the triangle on the left side of SuperAdventure.cs) and delete the “Load” eventhandler line on line 124.

      Please let me know if that answer is not clear, or if it does not fix the problem.

      • ping an
        ping an January 5, 2025

        Hello Scott Lilly:
        Thank you very much for your help, the problem has been solved! Thank you again for your prompt and able answer, which was very friendly to non-native English speakers。

Leave a Reply

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