Open links in new tab
  1. 123

    Encapsulation is a fundamental concept in object-oriented programming (OOP) that involves bundling data and methods that operate on that data within a single unit, typically a class. This mechanism helps to hide the internal state and functionality of an object from the outside world, allowing access only through a public set of functions.

    Key Principles of Encapsulation

    Encapsulation ensures that the internal state of an object is protected from unintended interference and misuse. This is achieved by:

    • Declaring the variables of a class as private.

    • Providing public methods to access and modify these variables, known as getter and setter methods.

    Example of Encapsulation in C#

    Here is a simple example to illustrate encapsulation in C#:

    using System;

    public class DemoEncap
    {
    // Private variables
    private string studentName;
    private int studentAge;

    // Public properties to access and modify the private variables
    public string Name
    {
    get { return studentName; }
    set { studentName = value; }
    }

    public int Age
    {
    get { return studentAge; }
    set { studentAge = value; }
    }
    }

    class Program
    {
    static void Main()
    {
    // Creating an object of DemoEncap
    DemoEncap obj = new DemoEncap();

    // Setting values using properties
    obj.Name = "Ankita";
    Continue reading
    Feedback
  1. Some results have been removed
Refresh