Programming in C#, Part 9: Encapsulation & Properties (Namespaces Too!)

We’ll be talking about the practice of encapsulation, and mixing in the use of properties as well. You will want to review the tutorial on classes and accessibility types if you don’t remember it: here. Any new concepts that won’t be explained will be in bold, signifying you should do some googling on the subject yourself.

Properties

The basic explanation of a property, is that it’s a function and variable’s love child. It’s a variable disguised to have functionality, syntactic sugar for a get/set function. Traditionally people would make the variable private and have a Get() and Set() function to do this same thing. In C# we have properties. You would call it and use it like a variable, but internally it works differently. Let’s take a look at a basic example:

int someNumber = 0;

int SomeNumberDouble
{
    get
    {
        return someNumber;
    }
    set
    {
        someNumber = value * 2;
    }
}

Properties use get and set, where get allows you to return a value (like when you’re getting a value from a variable) and set gives you a value that is passed in. If you do SomeNumberDouble = 5, then value in this case will be 5, and so someNumber will be set to 10. This is a pretty silly example, but you could use this in a number of cases.

bool IsNumberPositive { get { return someNumber >= 0; } } is one example, simple to just check if this number is positive.

Another example would be if you had a game with a health bar, and you wanted to update the health bar everytime the health was changed.

int health; //Backing field
int Health
{
    get { return health; }
    set { health = value; UIManager.UpdateUI(); }
}

Here it just calls a function to update the UI when it sees you’ve set the health to something different.

Encapsulation

Encapsulation is a fundamental idea of OOP, where we keep our privates to ourself. You may have asked yourself when making a class, why not just make everything public? Well because that’s insanity.

The idea is to keep everyone on an accessibility level that we control, so when using it outside of this class only the data we want is changed. This is good for team environments especially, so someone doesn’t accidentally change an incorrect value.

So let’s say we ignored encapsulation and made a Player class with all public values:

class Player
{
    public Player(string _firstName, string _lastName)
    {
        firstName = _firstName;
        lastName = _lastName;
    }
    public int health;
    public int Health
    {
        get { return health; }
        set 
        { 
            health = value; 
            UIManager.UpdateUI(); 
            if(IsDead)
                Die();
        }
    }

    public bool IsDead { get { return health <= 0 } }
    public string firstName;
    public string lastName;
    public string Name
    {
        get { return firstName + " " + lastName; }
    } 

    public bool Die()
    {
        //do something that kills the player
    }
}

Here everything is a mess. If someone changes thePlayer.health instead of thePlayer.Health then it will never check if the player has died, nor will it update the UI.

Also you can just kill the player at anytime, regardless of what their health is. This could cause unknown issues in the future. Anything could be changing the players values, multiply times and you would have no idea. Everyone would have their hands in the pot.

What we should do instead is only make the variables/functions public that we need outside the class available. In this case, that would be Name, Health, and IsDead. The rest can be changed or checked with these values.

This concept can also be used for a child/parent relationship, the child may not need to have access to all the values in the parent. Only the values the child needs to edit are worth making protected.

Even if you think you’ll remember what needs to be changed, you have no idea what you’ll forget in the future. Even just a minor mistake can cause issues that could’ve been easily avoided.

Namespaces

Namespaces are a pretty simple topic, they’re a way to organize your code. You’ve been using them in the past, anytime you’ve used a using at the top, for using System; or anything else. You’re including the System namespace in your file. You can wrap your code in a namespace in the same way to file it under a namespace.

namespace MyGame
{
    class Player
    {
         //code
    }
}

namespace MyGame.UI
{
    class UIManager
    {
        //code
    }
}

//Access
MyGame.Player
MyGame.UI.UIManager
//Or at the top
using MyGame;
using MyGame.UI;

 

Extra Practice

Have you already been using these practices? I would go back and check the past code you’ve written, make sure you’re supporting encapsulation. Make some properties to support the classes you’ve made. Improve what you’ve already written.

Support

Are you having trouble with understanding this tutorial? Please feel free to contact me via email at KoseckCory@gmail.com or message me on discord at 7ark#8194.

I would love to get feedback from people so I can add and improve these tutorials overtime. Letting me know what you’re confused about will let me update the tutorials to be more concise and helpful.

If you’re interested in supporting me personally, you can follow me on Twitter or Instagram. If you want to support me financially, I have a Patreon and a Ko-fi.

0 comments on “Programming in C#, Part 9: Encapsulation & Properties (Namespaces Too!)Add yours →

Leave a Reply

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