Access Modifier in C# .net

What is access modifier ?

Access modifier is just a keyword which is used to define how C# program can access the method or field. In C# there are 5 Kind of access modifier.

Public: When a method or attribute is defined as public, It can be accessed from any class in project or out side the project. For example in below class "Employee" the Name() method is public.
using System;
namespace tutorial       //Namespace
{
    public class Employee
    {
        public string Name()
        {
             return "Jhon";
        }
        private int PhoneNo()
        {
                return 123456;    
        }
        protected string Address()
        {
                return "India";
        }
        internal int Age()
        {
               return 21;
        }
        protected internal string Degination()
        {
                 return "Software developer";
        }
    }
}

Private: When a method or attribute is defined as private , It can be accessed in containing class only
not out side the class, In above  example class "Employee" attribute PhoneNo() can be accessed with
in class Employee only. Keep in mind if an attribute define within  class without modifiers, its
default access modifire is will be private.

Protected: When an attribute or method defined as protected it can be access in inherited classes and the same class the protected access modifier cannot applied to class only we can declare method and field as protected in our class. See in given below image.


Access Modifier





















Internal: If any method or field of the class is defined as internal  it means that  access is restricted for other class available in other project  but it can be access  and same class available in same project only.

Protect Internal: If  any method or field mark as Protect Internal it means that access is restricted for the other project's classes it can only access in same class and inherited class.



Post a Comment

Post a Comment (0)

Previous Post Next Post