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:

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

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:

The beginning of the class will look like this:

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:

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:

Your constructor will look like this:

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:

Now, you should have this:

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

Get it from GitHub: https://gist.github.com/ScottLilly/8cc706357c4b33e13a54

or DropBox: Lesson 05.1 – https://www.dropbox.com/sh/cgajmz7ax3932op/AABmSPu6FYA1-9KkikVFMBt7a?dl=0

 

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

 

90 thoughts on “Lesson 05.1 – Creating objects from classes

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

                 };

            }

    1. 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!

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

    1. Thanks. Can you check the SuperAdventure.Designer.cs file, and see if those labels are in it – and that they are Label controls (not textboxes, or something else)? If that looks correct, can you upload your solution (all its files, and all its files in its sub-directories) to Dropbox or GitHub?

        1. It looks like the names of the labels for hit points, gold, experience, and level start with the letter “I”, instead of a lower-case “L” (and “IbleHitPoints” has an “e” in it). Double-check the names of the labels with lesson 03.1, and see if that corrects the problem.

  3. 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…

     

     

    1. 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?

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

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

  5. 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!

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

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

      1. 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?

        1. 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?

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

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

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

      1. 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?

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

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

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

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

    1. 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. 🙂

Leave a Reply

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