Access Modifiers in C#

In our earlier posts of csharp tutorial series, you must have noticed public or private words written inside the code. Although we must have specified the meaning in context wherever we felt necessary. But now is the time to actually understand the meaning of all those words. They are called access modifiers, let's see what are these and what's their usage?


Access modifiers in csharp .net with examples



What Are Access Modifiers In C#?


Basically access modifiers are restricted keywords in .Net framework which decide the accessibility of members or type. Like access modifier can be specified for a class or its members(variables, properties or methods). Based on these keywords .Net compiler checks whether the members or type is allowed to be accessed externally or not. We will specify some good examples to let you understand. There are 5 access modifiers mentioned below

  • public
  • private
  • protected
  • internal
  • protected internal

One thing to note down is that these access modifiers are used mainly for members of the class, not for the class itself. Even if used, then these are used only for those classes which are declared inside another classes.

//The way access modifiers are used

// public class:
public class Car
{
    // protected method:
    protected void Accelerator() { }

    // private field:
    private int wheels = 4;

    // protected internal property:
    protected internal int Wheels
    {
        get { return wheels; }
    }
}


Let's understand each one of these access modifiers separately.


public keyword

public access modifier makes a member or type accessible from everywhere in the code, that means any assembly or any line of code can access a public type as it is free from any restrictions.
It is the most commonly used keyword in our early programming days, but later on we learn that everything should not be kept public.


private keyword

private access modifier makes a member or type accessible only from its containing type, that means private members of a class can only be accessed within the class itself. It is used to restrict the other classes to access our method or properties. Generally variables are kept private in a class and properties are made public, so that other classes can access properties and get/set values to variables.

A class can also be private when defined inside another class. It is usually done, when we need a specific class just inside our parent class for some purpose. The scenario is not so common.

Now let's take up an example of private members, where properties or methods or fields are kept private.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CheezyCodeApp
{
    public class PublicClass
    {
        public int publicProperty { get; set; }
        private int privateProperty { get; set; }
    }

    public class CheezyCode
    {
        static void Main()
        {
            //Class is accessible because it's public
            PublicClass publicClassObject = new PublicClass();

            //publicProperty is accessible because it's public
            publicClassObject.publicProperty = 10; 

            //For privateProperty compiler throws error saying inaccessible due to it's protection level
            publicClassObject.privateProperty = 10;
        }
    }    
}


Now in above example, we have a public class having a public and private property. Now when we accessed PublicClass in our Main() method, and created an instance of it. We will notice that intelli-sense of Visual Studio only shows publicProperty because as per the access modifier only public property is accessible.
Even if we try to write deliberately privateProperty than compiler will throw up an error saying privateProperty is inaccessible due to it's protection level.


protected keyword

protected access modifier is exactly similar to private but with an extra feature. The protected members can also be referred inside a class which is inheriting from it's containing type. Consider below example to understand more

public class PublicClass
    {
        public int publicProperty { get; set; }
        protected int privateProperty { get; set; } //Access set as protected
    }

    public class AnotherClass : PublicClass //Inheriting from PublicClass
    {
        public int MyProperty
        {
            get
            {
                return privateProperty; //Accessible
            }
            set
            {
                privateProperty = value;
            }
        }

        public void PrintPrivateProperty()
        {
            //privateProperty is accessible
            Console.WriteLine(privateProperty);
        }
    }

Here in the above example we can notice that protected member is accessible inside the inherited class. But still the instance of the AnotherClass will not show privateProperty just like the case of private modifier. Protected just makes the member accessible inside the inherited class.


internal keyword

In .Net we have namespaces, we will be discussing in upcoming posts. Till that time understand it as a parent container which contains different classes and these classes can be then referred using a single namespace. Like in our first example, there is namespace declared CheezyCodeApp below 'using statements'. So in a different file I can refer PublicClass by writing CheezyCodeApp.PublicClass

So when we specify a type or member as internal then it is accessible only inside the containing namespace not everywhere like in case of public.


protected internal keyword

protected internal access modifier is exactly similar to internal but with an added accessibility. The protected internal members can also be accessed inside the classes which inherit the container class of these protected internal members.
So a protected internal member can be accessed by any line of code inside the namespace, also outside the namespace if another class inherits from its parent container.

So that's all for access modifiers. It will be difficult to understand at first, but as you become more mature in .Net coding then things will become more clear to you.

Let us know if you have any query or concerns. Happy Reading (refer full series here - C# Tutorial Index)

Comments

Popular posts from this blog

Create Android Apps - Getting Started

Polymorphism in Kotlin With Example