Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

Access modifiers in C#

Access modifiers in C#:

Encapsulation is one of the biggest advantages of OOP, it is a process of binding the data members and member functions into a single unit. Encapsulating data and methods ensures independency, and limited access.

You can use access modifiers to set the allowed access to not only classes, but also to all members of those classes.

C# five access Specifiers:

Public :

Accessible outside the class through object reference.

Private:

 Accessible inside the class only through member functions.

Protected :

Just like private but Accessible in derived classes also through member functions.

Internal :

Visible inside the assembly. Accessible through objects.

Protected Internal :

Visible inside the assembly through objects and in derived classes outside the assembly through member functions.

Example:

namespace TestApp
{
public class student
    {
        //private
        private string StudentCategory;
        //public
        public string studentName { get; set; }
        //internal
        internal string InstituteName { get; set; }
        public static int numberOfStudents = 0;
        public student()
        {
            numberOfStudents++;
        }
 
        public student(string caetgory)
        {
            StudentCategory = caetgory;
        }
 
        publicbool isEligibleForReservation()
        {
            if (StudentCategory !="Open")
            {
                return true;
            }
            else
                return false;
        }
    }
}


namespace TestApp
{
class Program
    {
static void Main(string[] args)
        {
            var firstStudent = new student("Open");
  //public property firstStudent.studentName = "Nagnath Kendre";
  //internal property use            firstStudent.InstituteName = "JNEC";
            Console.WriteLine("Eligible for reservation :" + firstStudent.isEligibleForReservation());
            var otherStudent = new student("OBC");
            otherStudent.studentName = "Balaji Kendre";
            otherStudent.InstituteName = "PLGPL";
            Console.WriteLine("Eligible for reservation:" + otherStudent.isEligibleForReservation());
 
            var StudentsCount=student.numberOfStudents;
 
            Console.WriteLine("Number of students :" + StudentsCount);
           
        }
     }
  }
 

 

Invalid entry,please enter valid data.

Loading