Search code examples
c#unity-game-engineencapsulation

Clarifying my Understanding of Encapsulation in C#


I've been trying to figure out encapsulation for the past couple days and was wondering if my understanding is correct.

Is encapsulation when you make a class or a struct, make private variables and methods inside of the class or struct that you don't want other classes or structs to access, and then create public methods to read, write, or use the private variables and methods inside of other classes or structs?

If so, why would you do this? How would you know when to use this? What advantage does this have over not using encapsulation? If possible, could an example be provided of some "bad" code that would benefit from encapsulation?

Thanks for taking the time to read my question.


Solution

  • Encapsulation is used to more explicitly define [intended] behavior of a class.

    Say you have a Person class like so:

    public class Person
    {
        public int Age { get; set; }
        public string Name { get; set; }
    }
    

    A [real] Persons age is only ever going to go up, so why would you allow anyone to reassign it?

    Instead you can encapsulate the age so that it has to follow its intended behavior (at the cost of writing a bit more code to handle assigning / getting the value) like so:

    public class Person
    {
        private int _age = 0;
        public int Age { get => _age;  }
        public string Name { get; set; }
    
        public void Birthday()
        {
            _age += 1;
        }
    }
    

    This way you can guarantee that the age will never go down.