C# Interview Questions

36 Questions
C# Programming

C# Programming

Web DevelopmentFrontendBackendGame Dev

Question 9

What is encapsulation in C#?

Answer:

Encapsulation is one of the four fundamental principles of object-oriented programming (OOP) and is used to bundle data and methods that operate on the data within a single unit called a class. Encapsulation helps protect the internal state of an object from unintended or unauthorized access and modification. This is achieved by restricting access to certain components of an object and only exposing what is necessary through public methods or properties.

Key Concepts of Encapsulation

  1. Data Hiding:

    • Encapsulation allows a class to hide its data members (fields) from direct access by external code. This is typically done by making the data members private or protected.
    • Access to these data members is controlled through public methods (getters and setters) or properties.
  2. Access Modifiers:

    • C# provides several access modifiers to enforce encapsulation:
      • private: Members are accessible only within the same class.
      • protected: Members are accessible within the same class and by derived classes.
      • internal: Members are accessible within the same assembly.
      • public: Members are accessible from any code.
      • protected internal: Members are accessible within the same assembly or by derived classes.
      • private protected: Members are accessible within the same class or derived classes within the same assembly.
  3. Properties:

    • Properties in C# provide a flexible mechanism to read, write, or compute the values of private fields. They are declared with a get accessor and/or a set accessor.
    • Properties allow for controlled access and validation of data.

Benefits of Encapsulation

  1. Data Protection:

    • Encapsulation helps protect the internal state of an object from unintended or unauthorized changes, reducing the risk of errors and improving data integrity.
  2. Modularity:

    • Encapsulation allows a class to be treated as a self-contained unit, promoting modularity and making the code easier to understand, maintain, and test.
  3. Code Maintenance:

    • Changes to the internal implementation of a class can be made without affecting external code that uses the class, provided the public interface remains unchanged.
  4. Reusability:

    • Encapsulation promotes reusability by allowing classes to be used as building blocks in different parts of an application without exposing internal details.

Example of Encapsulation in C#

Here’s an example to illustrate encapsulation:

public class Account
{
    // Private fields
    private string accountNumber;
    private double balance;

    // Public property for accountNumber
    public string AccountNumber
    {
        get { return accountNumber; }
        private set { accountNumber = value; }
    }

    // Public property for balance
    public double Balance
    {
        get { return balance; }
        private set
        {
            if (value >= 0)
            {
                balance = value;
            }
        }
    }

    // Constructor
    public Account(string accountNumber, double initialBalance)
    {
        AccountNumber = accountNumber;
        Balance = initialBalance;
    }

    // Method to deposit money
    public void Deposit(double amount)
    {
        if (amount > 0)
        {
            Balance += amount;
        }
    }

    // Method to withdraw money
    public void Withdraw(double amount)
    {
        if (amount > 0 && amount <= Balance)
        {
            Balance -= amount;
        }
    }
}

In this example:

  • The Account class encapsulates the fields accountNumber and balance.
  • These fields are private and cannot be accessed directly from outside the class.
  • Public properties AccountNumber and Balance provide controlled access to the private fields.
  • The Deposit and Withdraw methods allow for modifying the balance in a controlled manner, ensuring that the balance cannot become negative.

Conclusion

Encapsulation in C# is a crucial concept that helps protect an object's internal state, promotes modularity and reusability, and improves code maintainability. By using access modifiers and properties, developers can control how data is accessed and modified, ensuring that the object's integrity is maintained while providing a clear and usable interface for external code.

Recent job openings