Home » C# Basics » 07 - More C#
7

Access Modifiers

Explains what access modifiers are and how it relates to classes

In the previous section, we have learned that the derived class inherits the members of the base class. In reality, not all members of the base class are inherited. In the Person class, there are three fields - name, age and gender. These three fields are not inherited in the Student class because they are declared as private in the base class. Since the properties that access them in the base class are declared as public, these properties are inherited by the Student class and that is why the object of the Student class is able to access them. The words private and public are known as access modifiers.

Access modifiers are keywords used to specify the accessibility of a member or a type. C# has the following access modifiers:

public, private, protected, internal and protected internal. Among these, public, private and protected access modifiers are more commonly used. The public members of a class are inherited by the derived class. They can be accessed in the other parts of the program (in the Main() method, for example). The private members are not inherited by the derived class and they cannot be accessed in the other parts of the program. The fields of a class are generally declared as private. The protected members of a class can be inherited but they cannot be accessed in the other parts of the program. Therefore, if we want a member of the class to be inherited by the derived class but not accessible to the other portions of the program, we should give it protected access.