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. Evan
    Evan June 8, 2018

    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?

    • Scott Lilly
      Scott Lilly June 8, 2018

      Did you create one of the projects with a different name? If so, you might find the answer in Lesson 02.2B – Fixing the namespace.

      If that doesn’t fix the errors, can you upload your solution (including the directories under it, and all the files in those directories) to GitHub or Dropbox, so I can look at it?

  2. Sam
    Sam June 18, 2018

    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…

    • Scott Lilly
      Scott Lilly June 18, 2018

      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.

  3. joshua
    joshua July 2, 2018

    there is a red line under the engine part of the using engine section how do I fix it?

    • Scott Lilly
      Scott Lilly July 2, 2018

      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.

      • joshua
        joshua July 2, 2018

        they did not fix the problem is it because I’m on a new version of visual studios

        • Scott Lilly
          Scott Lilly July 2, 2018

          This program works in the newest version of Visual Studio.

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

  4. 101code
    101code August 29, 2018

    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?

    • Scott Lilly
      Scott Lilly August 29, 2018

      Make sure your Miner class is “public”.

      If that is not the problem, can you upload your solution (including the directories under it, and all the files in those directories) to GitHub or Dropbox, so I can look at it?

      • 101code
        101code August 29, 2018

        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!

        • Scott Lilly
          Scott Lilly August 29, 2018

          You’re welcome. Let me know if you encounter anything else.

  5. Nick
    Nick November 26, 2019

    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!

  6. Dev
    Dev March 14, 2020

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

    • Scott Lilly
      Scott Lilly March 14, 2020

      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.

  7. logaa
    logaa June 22, 2020

    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?

    • Scott Lilly
      Scott Lilly June 23, 2020

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

  8. Anurag Kotamraju
    Anurag Kotamraju July 21, 2020

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

    • Scott Lilly
      Scott Lilly July 21, 2020

      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.

      • Anurag Kotamraju
        Anurag Kotamraju July 22, 2020

        What is the difference those two kinds of initiation? Where and what does it change?

        • Scott Lilly
          Scott Lilly July 22, 2020

          There’s no difference, other than maybe a few micro-seconds between when the Player object is instantiated. It’s mostly a style preference.

  9. Justin Habel
    Justin Habel September 2, 2020

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

    • Scott Lilly
      Scott Lilly September 2, 2020

      Hi Justin,

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

  10. Joseph
    Joseph October 3, 2020

    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!

    • Scott Lilly
      Scott Lilly October 3, 2020

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

  11. Eric
    Eric January 25, 2021

    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;
    }

  12. Aaron
    Aaron March 8, 2021

    Hi, so I’m pretty new to coding so I’ve got a few questions, but when I was creating labels 5-8 amd something called “SuperAdventure_Load” I created their event handlers and was wondering how to remove them properly because when deleting the “btnTest” I had to go to the “call stack” and put // before all the lines associated with btnTest and it seemed to have worked, I’m just unsure if that was the right way of doing it. and lastly when I wrote _player = new Player(); it appeared with the squiggly line.

    Thank you

    • Scott Lilly
      Scott Lilly March 8, 2021

      Hi Aaron,

      The SuperAdventure_Load could have been created if you accidentally double-clicked on the SuperAdventure form while in the Design mode. Visual Studio tries to “help” you by creating an eventhandler and a function for it. You can read more about eventhandlers in Lesson 21.3.

      For the squiggly line, did you add a “using Engine;” line at the top of the SuperAdventure class? If that doesn’t solve the problem, can you upload your solution (including the directories under it, and all the files in those directories) to GitHub or Dropbox, so I can look at it?

      • Aaron
        Aaron March 8, 2021

        Hi thank you for responding but I managed to figure it out, I put a curly bracket in the code and it was interfering with a block (at least that’s what I think they’re called.)

        Thank you

  13. Morpheus
    Morpheus October 13, 2021

    Hello, So I wanted to some help on a certain error that keeps popping up whenever I try to run the program. This is what it says:

    Code Project File Line Suppression State
    CS8180 Engine Player.cs 12 Active

    Thanks

    • Morpheus
      Morpheus October 13, 2021

      It also has a Description section in the error list where it says { or; or=> expected. I tried to look up help on error code CS8180 but no help.

      • Scott Lilly
        Scott Lilly October 13, 2021

        Hi Morpheus,

        From the previous error message, I suspect the error is on line 12 of the Player class. The additional information where it says “{ or; or=> expected” makes me think the problem might be with the {get; set;} for the property on line 12. Maybe it’s missing a semi-colon.

        If that doesn’t help you find a solution, can you paste a copy of the complete Player class some place where I can look at it?

  14. K Harada
    K Harada December 17, 2021

    Thank you for this tutorial!
    I am very new and using the newest VS, whenever I go to try to assign it to read the engine I get this message:

    (Naturally, this also leads me into the red line issue as it’s not letting me reference the engine/see the class Player.)

    error:

    Project ‘..\ENGINE\ENGINE.csproj’ targets ‘net6.0’. It cannot be referenced by a project that targets ‘.NETFramework,Version=v4.7.2’

    I already tried a solution where it asked to delete the bin and obj files and retry it to no avail.

    I have literally no idea what I’m doing here. Is it possible to do a workaround of putting the class of player into a new class within that code (I’m looking at the solutions its suggesting).

    Thank you so much for all of this work!

    • Scott Lilly
      Scott Lilly December 17, 2021

      Hello,

      The error message is saying that the Engine project was built with .NET 6 and the other project was built with .NET Framework 4.7.2, and those two types of projects cannot work with each other.

      A (hopefully) quick history of .NET:

      Around 2000, Microsoft created “.NET Framework”. They kept adding to it over the years, until it reached version 4.8. This guide was written in 2014, and used .NET Framework.
      .NET Framework only ran on Windows. So, Microsoft started making a version of .NET that would also work on Linux and Macs.
      This new version was called .NET Core. It ran everywhere, but did not have all the functions that were available in .NET Framework.
      When you created a solution, all your projects had to either be .NET Framework or .NET Core. You cannot mix them in a solution.
      Microsoft eventually created .NET 5. This is the future of .NET. Microsoft stopped working on .NET Framework and .NET Core.
      Now, if your solution is in .NET 5 (or 6), all the projects must be in .NET 5 (or 6).

      To make things even more confusing, there is something called .NET Standard. Projects built in .NET Standard CAN be used by .NET Framework, .NET Core, and .NET 5+ projects.

      So, when you build the solution, you need to make sure you do not have projects with different types of .NET.

      There is not an easy way to convert project types. It’s probably easiest to start a new solution. When adding projects to this solution, make sure to pick the .NET Framework project types, like in this picture:

      Let me know if that was not clear, or if you have any other questions.

  15. Anonymous
    Anonymous January 1, 2022

    I just started out C# and I have to say this tutorial is really thorough and helpful, and the actual author, not just anyone else is taking the time to answer comments/questions; it’s a testament to your dedication, and thank you for that.

    • Anonymous
      Anonymous January 1, 2022

      Bro I just saw Scott reply to a comment in 2021 and this tutorial was made 3, almost 4 years ago. WOW!.

      • Scott Lilly
        Scott Lilly January 1, 2022

        I just checked the history of the lessons. The very first page was posted on November 26th, 2013. That’s even older than I thought it was.

        SimpleRPG_FirstPost

    • Scott Lilly
      Scott Lilly January 1, 2022

      You’re welcome. I’m glad to hear you enjoy it. 🙂

  16. Joe Faucon
    Joe Faucon January 5, 2022

    Using VS2019 (Both .Net Framework 4.7.2 on forms and libraries)

    I’m getting a Compiler Error CS0246 as if the reference isn’t going through, no name changes. I know it’s not linking the reference, I just don’t understand why.

    Also getting CS0116 compile error.

    I switched down to 4.5.2 and it didn’t make a difference.

    • Scott Lilly
      Scott Lilly January 5, 2022

      Hi Joe,

      Can you 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?

      Or, can you send a link to a screenshot of the full error message area?

      • Joseph Faucon
        Joseph Faucon January 5, 2022

        I knew it was a references issue… I couldn’t figure out the step I missed, which was enabling the reference to Engine.

  17. vassilios
    vassilios July 30, 2022

    My program will not show the values of, hit points, Experience, level, and gold.
    I have tried different ways of formatting this but they do not seem to fit and i can’t think of anything else.

    • Scott Lilly
      Scott Lilly July 30, 2022

      There are a few reasons why it might not be working. Can you 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 need help uploading to GitHub, here is a video that might help: https://www.youtube.com/watch?v=F-Azm-JvJmM

      • vassilios
        vassilios August 8, 2022

        I think i fixed there was a weird problem were engine was not being uploaded to github but i think i fixed it.

        • Scott Lilly
          Scott Lilly August 9, 2022

          I fixed the code in the solution and uploaded it to my GitHub. There were some problems with code in the SuperAdventure code-behind page and the form. I invited you to have access to the repository. GitHub should have sent you an email to accept. I suggest you download this code into a new directory and use this solution, instead of the current one.

          Here’s a video on how to download the code from the repository, if you aren’t familiar with how to do that: https://youtu.be/oWl7-lzrKhA

          Please let me know if there are any problems downloading or running the solution.

          • vassilios simeonidis
            vassilios simeonidis August 24, 2022

            sorry i took a break and forgot all about this comment. could you please resend the invite?

  18. Thomas
    Thomas February 21, 2023

    Hello Scott, so I am having the issue adding the Engine in the reference tab and the red squiggle under Engine and Player here. I when into the properties and changed the default namespace to SuperAdventure but it didn’t seem to help. Here are the errors and the github link at the end. I hope it I did that right as I am as green as one can get with this stuff.

    Project ‘..\Engine\Engine.csproj’ targets ‘net6.0’. It cannot be referenced by a project that targets ‘.NETFramework,Version=v4.7.2’. ElderBridge

    CS0246 The type or namespace name ‘Player’ could not be found (are you missing a using directive or an assembly reference?) ElderBridge D:\Thomas Scripts\ElderBridge\ElderBridge\ElderBridge.cs 17 Active

    CS0246 The type or namespace name ‘Engine’ could not be found (are you missing a using directive or an assembly reference?) ElderBridge D:\Thomas Scripts\ElderBridge\ElderBridge\ElderBridge.cs 11 Active

    https://github.com/DraugrReign/ElderBridge.git

    • Scott Lilly
      Scott Lilly February 22, 2023

      Hi Thomas,

      Since the lessons were originally created, Microsoft came out with new versions of .NET – which don’t work with the old versions. It looks like your Engine project is a .NET 6 Class Library project (the new type of .NET), and your UI project is .NET Framework 4.7.2 (the old type of .NET). Unfortunately, there isn’t a simple way to upgrade or downgrade them.

      The simplest solution is probably to delete the existing Engine from the solution (also deleting it from your disk) and recreating the Engine project as a .NET Framework 4.7.2 Class Library project. When you add the Engine project back in, you can type “framework” in the search box (see the attached image) and make sure the Class Library project you select says “.NET Framework).

      Let me know if that isn’t clear, or if it doesn’t work for you.

Leave a Reply

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