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

 

75 thoughts on “Lesson 05.1 – Creating objects from classes

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

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

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

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

Leave a Reply

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