C# Encapsulation

Encapsulation is one of the fundamental concepts of Object-Oriented Programming (OOP). It is the mechanism of restricting access to certain components of an object and exposing only the necessary parts of it. This allows the internal workings of an object to be hidden from outside, reducing the complexity and increasing security.

In very simple words - It's a way to protect the inner workings of our code, just like how a TV keeps its complex circuits hidden behind a panel while giving you simple buttons to control it.

Let’s look at an example with a Person class, this time using encapsulation to control access to the person's age and email. We'll ensure that the age is always a positive integer, and the email is in a valid format.

Example: Person Class with Encapsulation


using System ;
using System.Text.RegularExpressions;

public class Person
{
    // Private fields
    private string _name;
    private int _age;
    private string _email;

    //  Constructor to initialize the person with name, age, and email
    public Person(string name, int age, string email)
    {
        _name = name;
        Age = age;        // Use the Age property to set age with validations
        Email = email;    // Use the Email property to set email with validations
    }

    // Public property for Age with validation
    public int Age
    {
        get { return _age; }
        set
        {
            if (value > 0)
            {
                _age = value;
            }
            else
            {
                Console.WriteLine("Age must be a positive integer.");
            }
        }
    }

    // Public property for Email with validation
    public string Email
    {
        get { return _email; }
        set
        {
            // Simple email validation using regex
            if (IsValidEmail(value))
            {
                _email = value;
            }
            else
            {
                Console.WriteLine("Invalid email format.");
            }
        }
    }

    // Method to validate email format using regex
    private bool IsValidEmail(string email)
    {
        var emailRegex = new Regex(@"^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,}$");
        return emailRegex.IsMatch(email);
    }

    // Method to display person info
    public void DisplayInfo()
    {
        Console.WriteLine($"Name: {_name}, Age: {_age}, Email: {_email}");
    }
}

class Program
{
    static void Main()
    {
        // Create a Person object
        Person person = new Person("John Doe", 25, john.doe@example.com);

        // Display initial person info
        person.DisplayInfo();

        // Attempt to set invalid age
        person.Age = -5; // Invalid age

        // Attempt to set invalid email
        person.Email = "invalidemail.com"; // Invalid email format

        // Attempt to set valid age and email
        person.Age = 30; // Valid age
        person.Email = john.new@example.com; // Valid email

        // Display updated person info
        person.DisplayInfo();
    }
}

Explanation:

  1. Private Fields:
    • The Person class in above example has private fields for name, age, and email. These fields are not directly accessible from outside the class.

  2. Public Properties:
    • Age: The Age property here controls access to the _age field and ensures that the value will always be a positive integer.

    • Email: The Email property controls access to the _email field and ensures that the email is in a valid format using a simple regular expression (Regex).

  3. Validation:
    • The Age property checks if the value is positive even before allowing it to be set.

    • The Email property uses a regex pattern to validate if the format is of email (it must be something name@domain.com).

    • The IsValidEmail() method contains the regex logic to validate if the email is correctly formatted or not.

  4. Constructor:
    • The constructor here initializes the person's name, age, and email. The properties Age and Email are used to ensure that the values are valid when the object is created.

  5. DisplayInfo() Method:
    • This method displays the person's information (name, age, and email).

  6. Error Handling:
    • If an invalid age or email is set, then appropriate messages are printed into the console, but the internal state of the Person object is not modified unless the input is valid.

Benefits of Encapsulation in this Example:

  • Data Integrity: The Age and the Email properties ensures that the internal state of the Person object is always valid , therefore protecting it from invalid data (like negative ages and incorrectly formatted email addresses).

  • Control: The class controls how and when the data is changed, this allows us to validate or even rejecting invalid changes.

  • Simplified Interaction: External code interacts with the properties rather than the private fields directly. This simplifies interacting with the object and ensures proper handling of the internal state.

Output


Name: John Doe, Age: 25, Email: john.doe@example.com
Age must be a positive integer.
Invalid email format.
Name: John Doe, Age: 30, Email: john.new@example.com

Conclusion

In conclusion, think of encapsulation as being like a vending machine - you don't need to know how it works inside, you just need to know which buttons to press to get what you want. The machine handles all the complex stuff for you!

Encapsulation helps in protecting the integrity of the object’s state, simplifying the interface for interaction, and providing a way to enforce constraints on the object’s data. It is one of the core principles of object-oriented programming(OOP) that enhances both the robustness and maintainability of your code.