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

159 Comments

  1. m654
    m654 April 23, 2016

    Oh, nevermind my post, I put the line of code in the wrong place lol.

    • Scott Lilly
      Scott Lilly April 23, 2016

      No problem. After more than 35 years of programming, I still do that too, sometimes. 🙂

  2. Frederik
    Frederik May 12, 2016

    I like how noob friendly this tutorial is. In this step, I would have liked to see a class initializer in your script such as this: https://msdn.microsoft.com/en-us/library/bb397680.aspx

    It’s something that I have just figured out but that I wish I knew a long time ago.

            public SuperAdventure()
            {
                InitializeComponent();

                _player = new Player()
                {

                         CurrentHitPoints = 10,
                         MaximumHitPoints = 10,
                         Gold = 20,
                         ExperiencePoints = 0,
                         Level = 1

                 };

            }

    • Scott Lilly
      Scott Lilly May 12, 2016

      That is a nice way to set property values, since you see the property name next to the value (instead of only entering them in order). I’m going to do some clean-up on a couple of lessons this weekend and will mention that technique. Thanks!

  3. CA
    CA June 25, 2016

    Hey Your tutorial has been great, by far the best I’ve found, however I need some help. I added the
    lblHitPoints.Text = _player.CurrentHitPoints.ToString();
    lblGold.Text = _player.Gold.ToString();
    lblExperience.Text = _player.ExperiencePoints.ToString();
    lblLevel.Text = _player.Level.ToString();

    And it states when i try to build that the names lblLevel,lblExperience,lblGold,lblHitPoints
    do not exist in the current context.
    I’ve tried checking for capitals and spellings as well as punctuation and spaces, however i can not find what I’ve done wrong

  4. Gregor Fuchs
    Gregor Fuchs July 10, 2016

    I have a problem
    The error with Player _player still exists I added the using Engine; line, but the only quick action is to remove the lines which are not in use.

    Any solution how I can fix this ? I tried to rebuild it.

    The reference to “Engine” exists, and I don’t know what I can do…

     

     

    • Scott Lilly
      Scott Lilly July 10, 2016

      In Player.cs, is the class public? The code should look like this:

      namespace Engine
      {
      public class Player

      If it is missing the “public”, that could cause a problem.

      If that is not the problem, can you upload your solution (including all the directories and files) to Dropbox, or GitHub?

  5. roccio
    roccio December 11, 2016

    Im getting a NotImplementedException, that goes to line 136 on the designer when I run this section. I dont know what Im doing wrong, I’ve followed everything exactly as in the video.

    • Scott Lilly
      Scott Lilly December 11, 2016

      It sounds like there might be an extra eventhandler in the form. If you open SuperAdventure.Designer.cs, find line 136, and comment out that line (put two forward slashes “//” at the front of it), that might fix the error.

      You can read more about how eventhandlers work in lesson 21.3.

      Please tell me if that does not fix the problem.

      • Roccio
        Roccio December 11, 2016

        Yes! That worked! Thanks for the quick reply!

  6. WebDev Jack
    WebDev Jack January 23, 2017

    I found a conspicuously similar app on the windows store called “60 Second RPG” by David M. Williams. Is this one of your students? BTW the whole concept of learning to code by making a game is Très bien. Merci beaucoup!

    • Scott Lilly
      Scott Lilly January 24, 2017

      Thanks! I don’t know David, but I’m not surprised to see a game like that. We were both probably inspired by the old Bard’s Tale game. That’s what I was thinking of when I created this course.

      I’m glad you like the concept. I think it helps to have the lessons build on what you learn in the previous lessons. It adds more context to how the pieces connect.

  7. Incomplete
    Incomplete January 30, 2017

    Hello! I just wanted to say it’s been a great tutorial so far. But I’ve encountered an odd issue.

    When I type in using Engine it doesn’t remove the red lines under private Player _player;
    instead it grays using Engine out and says “using directive is unnecessary”.

    I’m not sure what I’m doing wrong, I have the Engine reference and everything is named properly. If it is any issue I am using Visual Studio 2015.

    • Scott Lilly
      Scott Lilly January 30, 2017

      Thanks! It should work with Visual Studio 2015. Can you upload your solution (including the files in the sub-directories) to GitHub or Dropbox? I can look at it Tuesday and see if I can find the source of the problem.

    • Scott Lilly
      Scott Lilly January 30, 2017

      I was just thinking… Check the Player class, and make sure it has “public”. If that isn’t there, that could explain why it is not visible inside the UI project.

      • Matt
        Matt May 1, 2017

        Hi Scott, i decide to use your program as an inspiration for a school project, but i’m sadly having the same kind of problem that Incomplete had, and i have no idea how to fix it, considering that Player is public and it keeps on graying out and underlining Engine as an error. Any tips on how to possibly fix it?

        • Scott Lilly
          Scott Lilly May 1, 2017

          Hi Matt,

          My first thought is that the UI project might not have a reference to the Engine project. Double-check the steps in Lesson 02.2, especially the comment in Step 2 and Step 6.

          If that does not fix the problem, can you please upload your solution (including all the sub-folders and files underneath it) to GitHub or Dropbox. so I can look at it?

  8. Jan
    Jan April 3, 2017

    Hi Scott, just started programming in C# for about a week and in my search for tutorials found your website. Started out with some books like Murach C# 2015 and C# 6 for programmers. But those books causes you nailbiting and give a lot of frustration. My personal thanks you put so much time and effort into these tutorials. My oppinion you should give us the opportunity to donate something. Thanks doesn’t pay your rent 🙂

    Anyway to the point: at this step in the tutorial 05.1 i got an error:

    Well the Murach book was usefull in some way it was easy to remove the error:

    SuperAdventure.Designer.cs line 49 i deleted this.label1.Click += new system.EventHandler(this.label1_Click);

    Now my question is, how is it possible i follow the tutorials to the letter and still get an error noone as i can see in past posts had this issue?

    Thanks again for the great tutorials and i will start the new one when i have finished this one.

    • Scott Lilly
      Scott Lilly April 3, 2017

      You’re welcome! 🙂

      The error could have happened if you accidentally double-clicked on one of the labels. Visual Studio would have tried to “help” you by creating an eventhandler. It would have added the line to the SuperAdventure.Designer.cs file, and created a new function in the SuperAdventure.cs file. If you later copy-pasted my source code for the SuperAdventure.cs file, that source code would not include the function that was created. However, there would still be the eventhandler in SuperAdventure.Designer.cs. That would cause the error – the eventhandler looking for a function that does not exist.

      You can read more about how eventhandlers work in Lesson 21.3.

      Please tell me if you still have questions about this.

  9. Jonny
    Jonny April 8, 2017

    Just a question: Is there a difference between converting int to string via .ToString and Convert.ToString();?
    Because Convert.ToString(…); seems to have some problems here.

    • Scott Lilly
      Scott Lilly April 11, 2017

      Using Convert.ToString() will handle nulls (not raise an error), while .ToString does not.

      What problem are you seeing?

    • Scott Lilly
      Scott Lilly May 21, 2017

      Make sure that your Player class has “public”, so it can be seen in the UI project.

      So, line 9 should look like this:

      public class Player

      • Hoang Anh
        Hoang Anh May 29, 2017

        I have the same problem. When I type “using Engine”, the red lines under private Player _player are not removed. Instead, it grays using Engine out and says “using directive is unnecessary”.

        I fixed that by changing “using Engine” to “using ClassLibrary1”.

        I am using VS2017. Maybe now it requires referencing to the namespace instead of the project?

        • Scott Lilly
          Scott Lilly May 30, 2017

          The “using” is always for a namespace. Normally, when you create a project, the project name is also the namespace name. However, if you create a project named “ClassLibrary1”, and rename it to “Engine”, the project still uses “ClassLibrary1” as its namespace. I haven’t created any new programs in Visual Studio 2017 – I’ve only used it for projects that were created in VS 2015. But, I believe it works the same as VS 2015.

          There is some more information on how a project sets its namespace in Lesson 02.2B

  10. Hải Long
    Hải Long June 25, 2017

    private void SuperAdventure_Load(object sender, EventArgs e)
    {

    }

    • Hải Long
      Hải Long June 25, 2017

      I don’t know what is this? When I delete it, just have a error in Design*

      • Scott Lilly
        Scott Lilly June 25, 2017

        If you accidentally double-clicked on the form, when you were in Design mode, Visual Studio will create this function. It also creates an “eventhandler” in SuperAdventure.Designer.cs. If you delete the function in SuperAdventure.cs, you also need to find the eventhandler line in SuperAdventure.Designer.cs, and delete it. The line number for the eventhandler should be in the error message you are seeing.

        Please tell me if you cannot find the line in SuperAdventure.Designer.cs, or if that does not fix the error for you.

  11. Matthew Prince
    Matthew Prince June 28, 2017

    Hi Scott,

    Thanks for helping!

    I couldn’t ‘using Engine’. I fixed it by deleting the reference to SuperAdventure under Engine, and then adding a reference to Engine in SuperAdventure

    Surely this will give me problems later lol off to a good start

    • Scott Lilly
      Scott Lilly June 28, 2017

      You’re welcome! Please tell me if you encounter any other problems.

  12. Jason Bennet
    Jason Bennet June 29, 2017

    Good Morning Mr. Lilly,

    I thank you for taking the time to post this tutorial. I have been hobby programming since I had a Vic20 🙂 After many years of trying I still can not wrap my head around OOP. In your travels have you come across any modern languages that aren’t Object oriented? I miss VB6! I understand the benefits of reusable code and not making a pot of spaghetti, but I code alone and don’t mind if I copy and paste novels 🙂

    Thank you for any ideas you might have,

    An old code bloated VBA Programmer

    • Scott Lilly
      Scott Lilly July 2, 2017

      Hello,

      You’re welcome. It sounds like we started programming around the same time. My first computer was a Radio Shack Color Computer, in 1980. 🙂

      Right now, the most popular non-OOP language is probably JavaScript. You might want to look at AngularJS, or Node.js. People are using Node.js to write full applications – to run on servers.

      “Functional” languages are another non-OOP types of language (although, you can have some of them act like OOP languages, if you want). F# is Microsoft’s .NET functional language. Some other functional languages to look at are: OCaml, Haskell, and Erlang.

      There are a lot of options out there. So, you should be able to find something that lets you write programs how you like. 🙂

  13. CodingCareBear
    CodingCareBear July 21, 2017

    Hi!
    Thanks for the cool tutorial! I think it might be a bit more foolproof to not specify on which line code should be inserted but in which part of the code.
    Looking forward to the rest of this tutorial!

    • Scott Lilly
      Scott Lilly July 23, 2017

      You’re welcome. For new lessons, I’m trying to show the code in video – so it’s easier to see exactly where the code needs to change.

  14. Court
    Court September 25, 2017

    Just a head up, be sure to put the .Text behind the label name when assigning the values in step 6. It will cause you much headache. ha ha

  15. Adam K
    Adam K December 7, 2017

    Was getting a red line under Engine and Player, saying they are not referenced properly.

    Found that the namespace wasn’t setting automatically, even if I changed it in preferences, basically trying to utilise Engine wasn’t finding the namespace.

    Turns out my code was like this:
    -Player.cs-
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace ClassLibrary1 <— This needed changing to Engine
    {
    public class Player…

    I changed the WindowsFormsApplication1 namespace in SuperAdventure.cs to SuperAdventure.

    Hope this helps

    • Scott Lilly
      Scott Lilly December 7, 2017

      Hi Adam,

      Did you update the “Default Namespace” in the Properties of the Engine project, like in Lesson 02.2B (fixing the namespace)? If you do that, make sure you save the project (and it might be best to close Visual Studio and re-open it). If that doesn’t work, you will probably need to fix the namespace in all the other classes you create in the Engine project.

  16. Ben
    Ben January 17, 2018

    Every time I try to run the program, it says that SuperAdventure already exists, change the name, or something to that effect. I’ve tried making it from scratch like 6 times, since I keep failing or changing something that makes a dozen errors, and I guess that is what is causing the problem. Is there some way to delete its knowledge of my previous failures?

    • Ben
      Ben January 17, 2018

      “A file or folder with the name ‘SuperAdventure.resx’ already exists. Please give a unique name to the item you are adding, or delete the existing item first.”

      … is exactly what it says when i try to run it.

    • Scott Lilly
      Scott Lilly January 17, 2018

      Sometimes, if you “delete” a file in Visual Studio, it only removes it from the solution. The file is not deleted. So, if you try to add another files with the same name, the file is still there.

      If the file is not included in Solution Explorer (in Visual Studio), use Windows File Explorer to see if the file is still in the directory. Then, you can delete it through File Explorer.

      Please tell me if that does not solve the problem.

  17. Daniel
    Daniel February 4, 2018

    Hey Scott,

    almost right away on this step:
    “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.”

    I get a problem from SuperAdventure.Designer.cs

    line 124: this.Load += new System.EventHandler(this.SuperAdventure_Load);

    generates error

    Severity Code Description Project File Line Suppression State
    Error CS1061 ‘SuperAdventure’ does not contain a definition for ‘SuperAdventure_Load’ and no extension method ‘SuperAdventure_Load’ accepting a first argument of type ‘SuperAdventure’ could be found (are you missing a using directive or an assembly reference?) SuperAdventure C:\Users\a*****\source\repos\SuperAdventure\SuperAdventure\SuperAdventure.Designer.cs 124 Active

    Not sure if I missed a step somewhere back regarding this line or if this is an effect of using VS2017.

    I just commented out the line for now. Not sure if it’s okay to remove.

    • Scott Lilly
      Scott Lilly February 4, 2018

      Hi Daniel,

      If you accidentally double-click on the SuperAdventure form’s Design screen, Visual Studio will try to help you and create an “eventhandler” – although, you don’t really want one here. You can learn more about them in Lesson 21.3.

      You are safe deleting that line, or leaving it commented out.

  18. Frenzy
    Frenzy February 16, 2018

    Hey Scott,

    I’ve been able to follow your tutorial with much excitement through and through. Sad part is I cant stay on it continuously.

    I’m facing an issue, not programming wise but rather, remembering wise. After I’m done with a chapter, I can remember it for a while but then completely and utterly forget what I learned in a day or so. I can’t figure out what to do. Any suggestion for this silly question would be greatly appreciated. 🙂 Thanks.

    • Scott Lilly
      Scott Lilly February 17, 2018

      Maybe try this: When you’re going through a lesson, write notes from the lesson on paper (I’ve heard this helps people remember). Then, after the lesson, read through your notes.

      Also, realize that you won’t learn everything with your first program. If you write another program, you’ll remember “this is like the thing I learned before.” Then, you look back at your notes and figure out how to do what you need for your new program. After a few times, you should remember the basics. Then, as you write more programs, you’ll remember more.

  19. LucaLissa
    LucaLissa May 15, 2018

    I had the “using Engine” problem and it is caused by circular dependency. make sure to add engine as a reference to SuperAdventure project. instead to add reference to Engine project.

    • Scott Lilly
      Scott Lilly May 15, 2018

      Yes, you definitely want to be careful when setting the references. Some of the solutions I work with have over 100 projects in them. Managing the references takes a lot of effort.

Leave a Reply

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