Home > DeveloperSection > Blogs > Exploring the Role of Access Specifier in C#

Exploring the Role of Access Specifier in C#


C# C# 
Ratings:
0 Comment(s)
 4372  View(s)
Rate this:

Exploring the Role of Access Specifier in C#


In this blog I am trying to explain the concept of exploring the role of access specifier in C#.

As name suggest access specifiers/modifiers are responsible for specifying or modifying some things; I don’t know what change made by these modifiers at this level, and how they behaved after this significant change. Now I also have not much idea where these modifiers are enforced (works).

Note: please don’t be confused with specifiers and Modifiers, both are same at current context, and we use these terms interchangeably in further discussion.

Introduction:

 

Access modifiers are the keyword provided by C# to modify the access scope of particular elements (objects and its members etc.). These modifiers basically add prior to any element and dramatically changed the behavior of element (members). The behavior are changed in term access scope/visibility of that element of in whole program (i.e which able to access particular data, which not as well)

These modifiers are as follows:

1.      Public

2.      Internal

3.      Protected internal

4.      Protected

5.      Private

Public modifiers (global modifiers)

 

As name suggest public modifiers change the access visibility of particular element as global.  I.e. it exposes the element for public use; there is no restriction for accessing that element from any unit of pregame either it is from same assembly or from different assembly, it does not matter at all.

In brief public access modifiers is assessable any type defined in same assembly or any other assembly (i.e. all class can access this element either in same assembly or in different assembly)

Internal modifiers

This is the second modifiers, which is limited a bit compare to public modifiers.  In Internal modifiers element are visible to the same assembly unlike public modifiers. In same assembly any one can access the   element modified by the internal modifies. It is visible to hole assembly and program as well.

 Protected Internal


This the third modifiers provided by the c#. In this access modifier the visibility falls in between of whole assembly and the derived class of that class which contains protected internal member. Basically protected internal is the union of protected and internal modifiers (i.e. it works as protected (easily inherited/accessible to its derived class along with exposed it for the current assembly.)

Protected modifiers

 

This the fourth number of modifiers supported/provided by the .net. In this modifies the visibility level is very high. This means it is not exposed to all, except the derived class of base class in which it is defined and in base class in itself.

Private modifiers


This is the fifth and the last access modifiers. This modifier is highly restricted or fully restricted for the outside class. In private modifiers the element is visible are accessible to the class in which it was defined. It doesn’t visible to any other class except to itself in which it was defined.

Let’s take simple demo to illustrate these concepts:   

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace AccessSpecifierInC_sharp_

{

    class Program

    {

        static void Main(string[] args)

        {

             UserDetails newuser = new UserDetails("u1023","12345","Shreesh","shukla","Allahabad","9825634169");

             Console.Write(" enter your loginId....");

             string logId = Console.ReadLine();

             Console.WriteLine();

             Console.Write("Enter your password:");

             string pass=Console.ReadLine();

            if (newuser.Userlogin(logId,pass))

            {

                Console.WriteLine("login successfull");

                AcceessUserDetails userDetails = new AcceessUserDetails();

                AccessUserCredential userCredential = new AccessUserCredential();

                Console.WriteLine(" -------------------AccessUserDetails-----------");

                Console.WriteLine("user name=>" + userDetails.GetUserName(newuser));

                Console.WriteLine("user name=>" + userDetails.GetuserAddress(newuser));

                Console.WriteLine("user name=>" + userDetails.getUserContactNo(newuser));

              //error sees method definition comment

                // Console.WriteLine("user name=>" + userDetails.getUserLogID(newuser )); 

               //error sees method definition comment

                //Console.WriteLine("user name=>" + userDetails.getUserpassword());              

               Console.WriteLine(" --------- END AccessUserDetails-----------");

                Console.WriteLine(" -------------------AccessUserCredential-----------");

                userCredential.ShowUserLogId();

                userCredential.ShowUserMoblie();

                //userCredential.ShowUserPassword();// error  see method definition coment

                Console.WriteLine(" ------------ END AccessUserCredential-----------");

                Console.ReadLine();

            }

            else

            {

                Console.WriteLine("login failed:");

                Console.ReadLine();

            }

        }

    }

    class UserDetails

    {

        protected string user_logid;

        private string user_pass;

        public string user_firstNmae;

        public string user_lastname;

        internal string user_address;

        protected internal string user_mobile_no;

        public UserDetails()

        {

        }

        public UserDetails(string logid, string upass, string ufname, string ulname, string uaddress, string ucellphone)

        {

            this.user_logid = logid.Trim();

            this.user_pass = upass.Trim();

            this.user_firstNmae = ufname.Trim();

            this.user_lastname = ulname.Trim();

            this.user_address = uaddress.Trim();

            this.user_mobile_no = ucellphone.Trim();

        }

        public bool Userlogin(string userId, string password)

        {

            if (user_logid.Equals(userId) && user_pass.Equals(password))

            {

                return true;

            }

            else

            {

                return false;

            }

        }

       

    }

    class AcceessUserDetails

    {

        /// <summary>

        /// this class does not derived UserDetails class,

        /// so this method can access only those member of class that are (public,internal,protected internal)

        /// thus this methods can easily access the"user.user_firstname and user.user_lastname";

        /// because these are declared  public in this type.

        /// </summary>

        /// <param name="user"> userdetail type </param>

        /// <returns></returns>

        public string GetUserName(UserDetails user)

       {

            return user.user_firstNmae + "" + user.user_lastname;

        }

        /// <summary>

        /// this method again able to access "user.user_address";

        /// because this field declared as "internal" access specifier

        /// here this method in same assembly where this class is declared; so we able to access this method easily;

        /// </summary>

        /// <param name="user"></param>

        /// <returns></returns>

        public string GetuserAddress(UserDetails user)

        {

            return user.user_address;

        }

        /// <summary>

        /// This method again able to access "user.user_address";

        /// because this field declared as "protected internal" access specifier

        /// here this method in same assembly where this class is declared; so we able to access this method easily;

        /// </summary>

        /// <param name="user"></param>

        /// <returns></returns>

        public string getUserContactNo(UserDetails user)

        {

            return user.user_mobile_no;

        }

        /// <summary>

        /// error due to "private" protection level;

        /// this will not be visible in this class.

        /// </summary>

        /// <param name="newuser"></param>

        /// <returns></returns>

        /*public string getUserpassword(UserDetails newuser)

          {

            return newuser.user_pass;

          }

        */

        /// <summary>

        /// error due to "protectd" protection level;

        /// this will also not be visible in this class.

        /// </summary>

        /// <param name="newuser"></param>

        /// <returns></returns>

        /*public string getUserLogID(UserDetails newuser)

          {

            return newuser.user_logId;

          }

        */

    }

    class AccessUserCredential : UserDetails

    {

        /// <summary>

        /// this methods is able to access the "user_logId" because it's access specifier is "protected"

        /// and protected member of base class is always accessicible to is derived class"AccessuserCredential"

        /// </summary>

        public void ShowUserLogId()

        {

            user_logid = "u1000";

            Console.WriteLine("user id after changerd=>" + user_logid);

        }

        /// <summary>

         /// here in this method fields "user_mobile_no" is visible because of tow reasons;

         /// first of all it is declared as "protected"; which in turn provide direct access to this fields

                 without creating object of that class.

        /// second things are that it is also declared as "internal"; which in turn exposes this method visibility to        assembly level.

        /// so (protected) u (internal) = protected internal

        /// </summary>

        public void ShowUserMoblie()

        {

             user_mobile_no = "9807161713";

            Console.WriteLine("user id after changerd=>" +  user_mobile_no);

        }   

        /// Note no other method is accessible to the base class  except public or protected.

    }

}

  Finally build and run the project, you will have following output 


I hope this article greatly helpful for understanding the basics of Access modifier in c#

Thanks.


Don't want to miss updates? Please click the below button!

Follow MindStick