Encapsulation in C# Classes

Hello! In this lesson, we're revisiting Encapsulation, Private Attributes, and Private Methods in Object-Oriented Programming (OOP). Imagine encapsulation as an invisible fence safeguarding a garden from outside interference, keeping data and methods safe within. Within this garden, certain plants (Private Attributes and Methods) are only for the gardener's eyes. These are crucial for making your classes more robust and secure!

Encapsulation Explained

Encapsulation is a fundamental concept in Object-Oriented Programming (OOP) that involves bundling data (attributes) and methods (functions) that operate on the data into a single unit, called a class. This concept also restricts direct access to some of an object's components, thereby preventing accidental interference and misuse of the data. If you were to code a multiplayer game, for instance, you could create a Player class, encapsulating data (health, armor, stamina) and methods (ReceiveDamage, ShieldHit, RestoreHealth).

public class Player {
    private int health;
    private int armor;
    private int stamina;

    public Player(int health, int armor, int stamina) {
        this.health = health;
        this.armor = armor;
        this.stamina = stamina;
    }

    public void ReceiveDamage(int damage) {
        health -= damage;  // Reduce health
    }
    
    public void ShieldHit(int armorDamage) {
        armor -= armorDamage;  // Decrease armor
    }

    public void RestoreHealth(int healthIncrease) {
        health += healthIncrease;  // Restore health
    }
}

class Program {
    static void Main() {
        Player player = new Player(100, 50, 77);
    }
}

Now, player is an instance of the Player class on which you can call methods.

Remark the Privacy

In C#, the private keyword designates an attribute or method as limited to the class itself, meaning it cannot be accessed directly from outside the class. Note that the constructor itself cannot be private.

public class PrivateExample {
    private string privateAttribute;  // Declare a private field

    public string PublicAttribute { get; set; }

    public PrivateExample() {
        PublicAttribute = "Public";
        privateAttribute = "Private";  // Initialize private attribute
    }

    public string GetPrivateAttribute() {
        return privateAttribute;
    }
}

class Program {
    static void Main() {
        PrivateExample example = new PrivateExample();
        Console.WriteLine(example.PublicAttribute);  // Works: logs "Public"
        Console.WriteLine(example.GetPrivateAttribute());  // Works: logs "Private"
        // Console.WriteLine(example.privateAttribute);  // Error: can't access private attribute from outside
    }
}

Private attributes and methods are inaccessible directly from an instance. This arrangement helps maintain integrity.

Private Attributes

Private Attributes, which can only be altered via class methods, limit outside interference. For instance, a BankAccount class might feature a balance private attribute that one could change only through deposits or withdrawals. If you try to access bankAccount.balance directly in the main method, it will throw an error because balance is private.

public class BankAccount {
    private decimal balance;  // Declare a private field

    public int AccountNumber { get; }

    public BankAccount(int accountNumber, decimal balance) {
        AccountNumber = accountNumber;
        this.balance = balance;  // Initialize the private attribute
    }

    public void Deposit(decimal amount) {
        balance += amount;  // Deposit money
    }

    public decimal GetBalance() {
        return balance;  // A public method to access balance
    }
}

class Program {
    static void Main() {
        BankAccount bankAccount = new BankAccount(1234, 100);
        Console.WriteLine(bankAccount.GetBalance());  // Works: logs 100
        // Console.WriteLine(bankAccount.balance);  // Error: can't access private attribute from outside
    }
}

Here, balance is private, thus ensuring the integrity of the account balance. It can't be accessed directly from outside the class.

Private Methods

Like private attributes, private methods are accessible only within their class. They are useful when you want to hide complex implementation details or helper functions from outside access. Here's an example:

public class BankAccount {
    private decimal balance;  // Declare a private field

    public int AccountNumber { get; }
    
    public BankAccount(int accountNumber, decimal balance) {
        AccountNumber = accountNumber;
        this.balance = balance;
    }

    // Private method
    private void AddInterest(decimal interestRate) {
        balance += balance * interestRate;  // Calculation of interest
    }

    // Public method calling the private method
    public void AddYearlyInterest() {
        AddInterest(0.02m);  // Adds 2% interest
    }

    public decimal GetBalance() {
        return balance;
    }
}

class Program {
    static void Main() {
        BankAccount bankAccount = new BankAccount(1234, 100);
        bankAccount.AddYearlyInterest();  // Works, calling a public method
        Console.WriteLine(bankAccount.GetBalance());  // Logs the updated balance
        // bankAccount.AddInterest(0.1m);  // Error: can't call a private method from outside
    }
}

Here, AddYearlyInterest() is a public method that calls the private method AddInterest().

Getters

In C#, properties provide a way to access and mutate private attributes indirectly while maintaining control over how values are retrieved or changed. This remains in line with the encapsulation principle by providing a controlled interface to interact with private data.

Properties allow access to the value of a private attribute in a safe, controlled manner. Here's how you can define a property for a private attribute:

public class BankAccount {
    private decimal balance;  // Declare a private field

    public int AccountNumber { get; }

    public BankAccount(int accountNumber, decimal balance) {
        AccountNumber = accountNumber;
        this.balance = balance;  // Initialize the private attribute
    }

    // Property for balance
    public decimal Balance {
        get { return balance; }
    }

    public void Deposit(decimal amount) {
        balance += amount;  // Deposit money
    }
}

class Program {
    static void Main() {
        BankAccount bankAccount = new BankAccount(1234, 100);
        Console.WriteLine(bankAccount.Balance);  // Works: logs 100
    }
}

In this example, the Balance property provides a safe way to access the private balance attribute.

Setters

Properties allow modification of the value of a private attribute while providing a controlled interface. Here’s how you can define a property with a setter for a private attribute:

public class BankAccount {
    private decimal balance;  // Declare a private field

    public int AccountNumber { get; }

    public BankAccount(int accountNumber, decimal balance) {
        AccountNumber = accountNumber;
        this.balance = balance;  // Initialize the private attribute
    }

    // Property for balance
    public decimal Balance {
        get { return balance; }
        set {
            if (value >= 0) {
                balance = value;
            } else {
                Console.WriteLine("Balance cannot be negative.");
            }
        }
    }

    public void Deposit(decimal amount) {
        balance += amount;  // Deposit money
    }
}

class Program {
    static void Main() {
        BankAccount bankAccount = new BankAccount(1234, 100);
        bankAccount.Balance = 200;  // Works: sets balance to 200
        Console.WriteLine(bankAccount.Balance);  // Works: logs 200
        bankAccount.Balance = -50;  // Logs: "Balance cannot be negative."
    }
}

In this example, the Balance property ensures that the balance is only set to non-negative values, adding a layer of validation.

By using properties, you can add logic for validating or transforming data, making your class more flexible and secure while adhering to encapsulation principles.

Lesson Summary and Practice

Great job refreshing your understanding of encapsulation, private attributes, and private methods concepts in C#! Correctly understanding and applying these foundational principles of OOP make your code concise, robust, and secure.

Coming up next is hands-on practice. Keep up the good work — exciting exercises are just around the corner!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal