Access Modifiers in C#

In most of the interviews people generally confused about the access modifiers. I am going to explain here about the access modifiers available in dot net and will provide a way to remember all these things and I am sure once reading this post you will not going to forgot abut the access modifiers.If we look at the MSDN we will see what actually it is, it is explained as "Access modifiers are keywords used to specify the declared accessibility of a member or a type" , in detail we can say that All types and type members have an accessibility level, which controls whether they can be used from other code in your assembly or other assemblies.
You can use the these access modifiers to specify the accessibility of a type or member when you declare it, In Dont Net (C#) we have the following available access modifiers (as provided on MSDN)
  1. Public
  2. Protected
  3. Internal
  4. Protected internal
  5. Private
Lets discuss each modifiers one by one and know about their functionality and uses in the framework. Lets start with public.

Public :

As per MSDN "The type or member can be accessed by any other code in the same assembly or another assembly that references it" or in simple words we can say that There are no restrictions on accessing public members.

Accessibly
  • Can be accessed by objects of the class
  • Can be accessed by derived classes
Example
 
class TestClass
    {
        public int Add(int a, int b)
        {
            return a + b;
        }
        public int Numbers;
    }

        class AnotherClass
        {
            public void GetData()
            {
                int a = 0;
                int b = 10;
                TestClass cl = new TestClass();
                //Direct Access to Members (All Variables and Methods which marked as Public)
               cl.Numbers =  cl.Add(a, b);

            }
        }
In the above example method Add and variable Numbers is marked as public in TestClass which is directly accessible to another class AnotherClass by creating the object of the member class.

Private :

As per MSDN "The type or member can be accessed only by code in the same class or struct" or in other words we can say that Private members are accessible only within the body of the class or the struct in which they are declared and access is the least permissive access level.

Accessibly
  • Cannot be accessed by object
  • Cannot be accessed by derived classes
Example
class TestClass
    {
        private int member1; // Private Member
        private int member2; // Private Member
        private int member3; // Private Member
        public int member4;  // Public Member
        public int member5; // Public Member
    }

    class TestInsideClass
    {
        void TestMethod()
        {
            TestClass obj = new TestClass();
            obj.member1 = 1; //will give error
            obj.member2 = 2; //will give error
            obj.member3 = 3; //will give error
            obj.member4 = 4; // OK
            obj.member5 = 5; // OK
        }
    }
If we compile the above piece of the code then we will get error for private members as shown below (click on the Image for clear view):
So due to private access modifier these variables are not accessible in the other classes but in case of nested class there is some difference, will discuss more about nested classes in another post soon.

Protected :

As per MSDN "The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class." or in simple words we can say that A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member. OR A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type. Accessibly
  • Cannot be accessed by object
  • By derived classes
Example
public class Class1
{
    protected int TestNumber;
}
public class Class2:Class1
{
    public int TestNumber2;
    public void TestMethod()
    {
        Class1 cl = new Class1();
        cl.TestNumber = 0; // Not Accessible, Will give error 
        Class2 cl2 = new Class2();
        cl2.TestNumber = 0; //Acessible
    }
}

If we see the above object of the class1 is not able to access it's prtected member but the object of the class which inherits class1 is able to access its protected member. If we will try to access protected member in above example then it will give the below error :
"Error 1 Cannot access protected member 'Class1.TestNumber' via a qualifier of type 'Class1'; the qualifier must be of type 'Class2' (or derived from it)"

Internal :

As per MSDN "The type or member can be accessed by any code in the same assembly, but not from another assembly." or in simple word or other words we can say that Internal members are accessible only within files in the same assembly (.dll).
Exception[1]: An internal virtual method can be overridden in some languages, such as textual Microsoft intermediate language (MSIL) using Ilasm.exe, even though it cannot be overridden using C#.
Accessbility
In same assembly (public)
  • Can be accessed by objects of the class
  • Can be accessed by derived classes
In other assembly (internal)
  • Cannot be accessed by object
  • Cannot be accessed by derived classes

Example
// TestAssembly1.cs
// compile with: /target:library
internal class BaseClass 
{
   public static int IntM = 0;
}

// TestAssembly2.cs
// compile with: /reference:TestAssembly1.dll
// CS0122 expected
class TestAccess 
{
   public static void Main() 
   {
      BaseClass myBase = new BaseClass();   // error, BaseClass not visible outside assembly
   }
}

Protected Internal:

As per MSDN "The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type."
 The protected internal accessibility level means protected OR internal, not protected AND internal. In other words, a protected internal member can be accessed from any class in the same assembly, including derived classes. To limit accessibility to only derived classes in the same assembly, declare the class itself internal, and declare its members as protected. Example
// public class: 
public class Tricycle
{
    // protected method: 
    protected void Pedal() { }

    // private field: 
    private int wheels = 3;

    // protected internal property: 
    protected internal int Wheels
    {
        get { return wheels; }
    }
}
The protected internal access modifier seems to be a confusing but is a union of protected and internal in terms of providing access but not restricting. It allows:
  • Inherited types, even though they belong to a different assembly, have access to the protected internal members.
  • Types that reside in the same assembly, even if they are not derived from the type, also have access to the protected internal members.
Here are the Images through which you can remember the accessibility of these modifiers. 
(click on the image for clear view)
Image 1:


Image 2:


Image 3

Image 4


A good Example from Codeppoject[http://www.codeproject.com/Articles/25078/C-Access-Modifiers-Quick-Reference]

   

  Refernces 1. MSDN [http://msdn.microsoft.com/en-us/library/ms173121.aspx]

Comments