Last modified on 11 November 2014, at 11:11

C# Programming/Encapsulation

Encapsulation is depriving the user of a class of information he does not need, and preventing him from manipulating objects in ways not intended by the designer.

A class element having public protection level is accessible to all code anywhere in the program. These methods and properties represent the operations allowed on the class to outside users.

Methods, data members (and other elements) with private protection level represent the internal state of the class (for variables), and operations that are not allowed to outside users. The private protection level is default for all class and struct members. This means that if you do not specify the protection modifier of a method or variable, it is considered as private by the compiler.

For example:

public class Frog
{
    private int _height = 0;
 
    // Methods
    public void JumpLow() { Jump(1); }
    public void JumpHigh() { Jump(10); }
 
    void Jump(int height) { _height += height; }
}

In this example, the public method the Frog class exposes are JumpLow and JumpHigh. Internally, they are implemented using the private Jump function that can jump to any height. This operation is not visible to an outside user, so they cannot make the frog jump 100 meters, only 10 or 1. The Jump private method is implemented by changing the value of a private data member _height, which is also not visible to an outside user. Some private data members are made visible by Properties.

Protection LevelsEdit

PrivateEdit

Private members are only accessible within the class itself. A method in another class, even a class derived from the class with private members cannot access the members. If no protection level is specified, class members will default to private.

namespace PrivateSample
{
    public class Person
    {
        private string _name;
 
        // Methods
        public Person(string name)
        {
            // Private members can only be modified by the internal methods or constructors of class
            this._name = name; 
        }
    }
 
    public class Entry
    {
        static void Main(string[] args)
        {
            Person OnePerson = new Person("Samanta");
            //OnePerson._name = "Sam"; // This causes a error of access level
        }
    }
 
===Protected===
Protected members can be accessed by the class itself and by any class derived from that class.
 
<source lang=CSharp>
namespace ProtectedSample
{
    public class Person
    {
        protected string _name;
    }
    /// <summary>
    /// When a class inherits from other class, it can access your protected and public members
    /// above your created members
    /// </summary>
    public class Warrior : Person
    {
        public void SetName(string name)
        {
            // Protected members can be accessed by internal methods or constructors of class
            // so, it can be accessed by inherit class too
            base._name = name;
        }
    }
 
    public class Entry
    {
        static void Main(string[] args)
        {
            Warrior OnePerson = new Warrior();
            OnePerson.SetName("Glades"); // OK
            // OnePerson._name = "Sam"; // This causes a error of access level too
            // protected members can not be accessed by external scopes
        }
    }
}

PublicEdit

Public members can be accessed by any method in any class.

namespace PublicSample
{
    public class Person
    {
        public string Name;
    }
 
    public class Entry
    {
        static void Main(string[] args)
        {
            Person BeautifulPerson = new Person();
            BeautifulPerson.Name = "Debora"; // OK, public member can be accessed by other scopes
        }
    }
}

It is good programming practice not to expose member variables to the outside, unless it is necessary. This is true especially for fields that should only be accessible over accessor and mutator methods (getters and setters). Exceptions are member variables that are constant.

InternalInternal

Internal members are accessible only in the same assembly and invisible outside it. If no protection level is specified for top level classes, they are treated as internal, and can only be accessed within the assembly.

namespace InternalSample
{
    public class Person
    {
        internal string Name;
    }
 
    public class Entry
    {
        static void Main(string[] args)
        {
            Person BeautifulPerson = new Person();
            BeautifulPerson.Name = "Debora"; // OK, internal member can be accessed by other 
            // scopes in same assembly supposing that Person is in another assembly, by example a 
            // library, the name cannot be accessed. In another assembly source, this causes an error:
            // BeautifulPerson.Name = "Debora"; // Cannot access internal member
        }
    }
}

Protected InternalProtected Internal

Protected internal members are accessible from any class derived from that class, or any class within the same assembly. So, it means protected or internal.[1]

Here, an example:

namespace InternalSample
{
    public class Person
    {
        protected internal string Name;
    }
 
    public class Entry
    {
        static void Main(string[] args)
        {
            Person BeautifulPerson = new Person();
            BeautifulPerson.Name = "Debora"; // As above...
        }
    }
}
 
public class Book : InternalSample.Person
{
    static void Main(string[] args)
    {
        InternalSample.Person BeautifulPerson = new InternalSample.Person();
        string aName = BeautifulPerson.Name; // Can be accessed, as Book is derived from Person
    }
}

ReferencesReferences

  1. Joe Mayo (2007-04-27). "Type Member Access Modifiers". http://www.csharp-station.com/: C# STATION. http://www.csharp-station.com/Tutorials/lesson19.aspx. Retrieved 2011-08-12. "Either code from derived type or code in the same assembly. Combination of protected OR internal."