Press "Enter" to skip to content

Lesson 08.1 – Setting properties with a class constructor

Lesson Objectives

At the end of this lesson, you will know…

  • What a class constructor is
  • How to use a class constructor to set the properties of an object, during the object’s instantiation
  • How a child (derived) class can call the constructor of its base class

 

Let’s clean up the code a little

Right now, in the SuperAdventure class, the code instantiates a Player object, then has five lines to set the properties of the player object. That works fine, but we can make that a little cleaner by doing all that in one line of code.

We do this by creating a new class constructor.

Every class starts with a default constructor. It’s what is run when you call “new Player()”. It builds and returns a new Player object.

However, we can make our own constructors that do more than this default action. So, we are going to make constructors that accept the values we want to store in the properties.

 


Link to video on YouTube

 

Step 1: Start Visual Studio and open the solution.

 

Step 2: To see how this works, we’re going to create a location object in our UI code (for a while). In the SuperAdventure project, right-click on SuperAdventure.cs and select “View Code”.

 

Step 3: Go to the end of line 21 and hit the enter key twice (to give us a little space). Then add in these lines:

Location location = new Location();
location.ID = 1;
location.Name = "Home";
location.Description = "This is your house.";

Here, we create a new Location object, and save it to the variable “location” (notice that the variable name is all lower-case, to make it different from the class). Then we assign values to the property of that object.

 

Step 4: Double-click on the Location class, in the Engine project, to start working with it. Go to the end of line 13 and hit enter twice. Then, add this code:

public Location(int id, string name, string description)
{
    ID = id;
    Name = name;
    Description = description;
}

This is our new constructor code.

It starts out with “public”, because we want to be able to create a new Location object from anywhere in the solution. Then it has the name of the class. After that, we see three “parameters” between the parentheses.

When you run a function, or method (like a constructor), it can accept values. These are called parameters. In C#, you need to declare the datatype of the parameter and its name. In this constructor, there are three parameters: id (an integer), name (a string), and description (another string).

Notice that the names of the parameters match the names of the properties, except they are all lower-case. By having a different case from the property, it’s more obvious when you’re working with the property and when you’re working with the parameter value. They don’t need to match the property name, but I do that to make it obvious what the parameters are going to be used for.

So, now when you call the Location constructor, you’ll need to pass in these three values.

On lines 17 through 19, we assign the values of the parameters to the properties in the class. Notice that the parameters (lower-case) are all on the right of the equal sign, and the properties (mixed-case) are on the left. The value on the right of the equal sign gets assigned to the property, or variable, on the left.

 

Step 5: Go back to the SuperAdventure code and you’ll see there is a red line under the “new Location()” code. That’s because we aren’t using the default constructor in the Location class anymore – we have our own custom constructor that wants three parameters.

If you remove the “new Location()”, and re-type it, you’ll see that as soon as you type the open parentheses “(” there is a tooltip that shows you the “method signature” (the parameters you need to pass to this method/constructor).

Change line 23 to this:

Location location = new Location(1, "Home", "This is your house.");

Now, when you construct a new Location object, you can pass in the parameters you want assigned to the properties. This makes your code a little shorter/cleaner. It is also a way of double-checking that you’ve set all the properties. If you manually set each one, like before, it’s easy to forget one. But with constructor that accepts parameters, you’ll know exactly how many have to be passed to it. If you forget one, you’ll see that red line.

 

Step 6: Double-click on the Quest class, in the Engine project, to start editing it. Add the following lines after the properties:

public Quest(int id, string name, string description, int rewardExperiencePoints, int rewardGold)
{
    ID = id;
    Name = name;
    Description = description;
    RewardExperiencePoints = rewardExperiencePoints;
    RewardGold = rewardGold;
}

Now the Quest class has a custom constructor that accepts values to use to set its properties.

 

Summary

You’re going to see custom constructors in many C# projects. It’s an easy way to ensure that your class has all needed properties set. You can also create one to do some other special tasks, which we’ll see a bit later.

 

Source code for this lesson

Source code on GitHub

Source code on DropBox

 

Next Lesson: Lesson 08.2 – Using class constructors with derived classes

Previous lesson: Lesson 07.1 – Inheritance and base classes

All lessons: Learn C# by Building a Simple RPG Index

24 Comments

  1. Will Cottrell
    Will Cottrell December 8, 2015

    Hi again! I hate to comment on another Lesson (I did on 6.1) but may i ask whether you deleted the line,


    Location location = new Location(1, "Home", "This is your house.");

    as in the video it looked like you did, though, in the explanation underneath it doesn’t say… Sorry again!

    • Scott Lilly
      Scott Lilly December 8, 2015

      No problem 🙂 If you have a question, it’s always better to ask.

      I’m at work, so I can’t check the video right now. But I probably deleted the line because we don’t actually need it in SuperAdventure.cs. That was just a convenient, temporary place to show how to instantiate the object with parameters.

  2. Will Cottrell
    Will Cottrell December 9, 2015

    Should I keep or delete the code then? Sorry I just don’t want to get a certain way through and for it not to work! Feel free to wait until you get back to work! Thanks!

    • Scott Lilly
      Scott Lilly December 9, 2015

      You can delete that line, because it instantiates an object that we never use. In a future lesson, you will replace all the constructor code anyway, to create the objects we actually use in the game.

  3. Will Cottrell
    Will Cottrell December 9, 2015

    Thanks so much!

  4. Theodor Edström
    Theodor Edström October 6, 2016

    The “location” coding is quite confusing as it says when i hold my mouse cursor over it “Error: ‘ClassLibrary1.Location.Location(int,string,string)’ is inaccessible due to it’s protection level” what should i do? cant find any Faults in my coding :/

     

    • Scott Lilly
      Scott Lilly October 6, 2016

      When you see that error message, it’s because the program is trying to use a class, but the “scope” of the class is not set so it can be used by that part of the program.

      Check the Location.cs file with the code here (source code). I think the problem is probably that line 9 does not have the “public” in it.

      Please tell me if that does not fix the problem.

  5. Noah Limes
    Noah Limes December 4, 2016

    So could we also create a constructor for the player class to assign the Gold, XP points, and Level?

    • Scott Lilly
      Scott Lilly December 4, 2016

      Yes. We’re going to do that in the next lesson.

  6. Michelle Nygaard
    Michelle Nygaard April 17, 2017

    My code keeps giving the error “Quest.Quest(int,string,string,int,int)’ must declare a body because it is not marked, abstract, extern or partial”

    public Quest(int id, string name, string description, int rewardExperiencePoints, int rewardGold);

    And i don’t know how to fix it. My code looks excactly like yours and i just can’t see the error /:

    • Scott Lilly
      Scott Lilly April 17, 2017

      You might see this error if you have a curly-brace in the wrong position. Double-check your class with the code at: https://gist.github.com/ScottLilly/9d6042780a563cabef12 – especially to make sure the curly-braces and parentheses are correct.

      If that does not fix the error, please post the code for your Quest class on Gist, and send me the link, so I can look at it.

  7. Louis Creed
    Louis Creed August 11, 2017

    Why does the Location class have to be put before the location object is defined but the Player class isn’t needed when _player object is defined?

    I.E.

    Location location = new Location(#, x, x);
    _player = new Player();

    Not

    Location location = new Location(#, x, x);
    Player _player = new Player();

    • Scott Lilly
      Scott Lilly August 11, 2017

      The datatype “Player” is only included when the variable is first declared. For the “_player” variable, that was already done on line 17 of SuperAdventure.cs.

  8. NotARobot
    NotARobot January 28, 2018

    Why don’t we write “private Location location;” as we did with player. Yea, i saw that it’s been said that it’s because we need class player more oftenly but it says me nothing :c i’m dummy

    • Scott Lilly
      Scott Lilly January 29, 2018

      When we create the “location” variable on line 23, we are only creating a variable that is used by the function. So, it does not need any “scope” (the “private” or “public” that sets the visibility). The “location” variable is only visible within the function – SuperAdventure’s constructor. If we wanted to create a “location” property, we would declare it outside the function, but inside the class. We would need to add a scope to that, if we didn’t want it to use the default scope.

      Let me know if that make sense, or if you still have questions.

      • NotARobot
        NotARobot January 30, 2018

        Thank you i got that around 45%. I’m gonna dig deeper in your course and believe that the per cent will increase.

  9. Bill
    Bill April 11, 2018

    Scott – Do you know what setting dictates whether to automatically replace my typed words with what Visual Studio thinks I’m attempting to type? When I type “Name” in this lesson, it’ll automatically replace it with “name”, same with “ID” to “id”. I’ve been trying to keep up with it, and pressing Esc every time I see the box pop up but since I’m still learning it takes up time and distracts an admittedly easily-distracted guy here.

    Thanks,
    Bill

    • Scott Lilly
      Scott Lilly April 11, 2018

      Hi Bill,

      It sounds like you want to turn off part of Intellisense. You can do that by clicking on the Visual Studio menu Tools -> Options…. Then, look under Text Editor -> C# -> Intellisense and try unchecking the options there – maybe “Show name suggestions”.

      Let me know if I didn’t understand the problem correctly, or if this doesn’t work for you.

    • Scott Lilly
      Scott Lilly April 25, 2018

      Hi Mackenzie,

      There is a semi-colon at the end of line 17 (after the list of parameters) that does not need to be there. Remove it and let me know if you still see the errors.

  10. Nathan
    Nathan December 8, 2020

    Hi, there!

    I’ve been using your tutorial, and I had a bit of trouble.

    I got this error:

    ‘object’ does not contain a constructor that takes 3 arguments

    In the Weapon.cs, here’s my code so far:

    https://pastebin.com/yA1xyyyg

    • Scott Lilly
      Scott Lilly December 9, 2020

      Hi Nathan,

      That weapon class looks like it’s the one from Lesson 08.2, which also has some changes that need to be made to other classes. Probably the best thing to do is go ahead to Lesson 08.2, make sure your classes have all the changes in that lesson, and see if that fixes the error.

      If you still see the error, 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. Samantha Schlaifer
    Samantha Schlaifer July 5, 2021

    Hello!

    When I add the line:

    Location location = new Location();

    Both “Locations” get the red squiggle with:
    “Location is inaccessible due to protection level”

    Do you know what I can do to fix this?

    Thank you!

    • Scott Lilly
      Scott Lilly July 5, 2021

      Hi Samantha,

      That error message means the current class cannot “see” the Location class. Check your Location class and make sure it has “public class Location”, not just “class Location”. By making the class “public”, it can be seen in other projects in the solution. If it only says “class Location”, the class has the default of “internal”, which means it can only be seen by other classes in the same project (not the whole solution).

      If that does not solve the problem, or if you have any questions about that, please let me know.

Leave a Reply

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