24 December 2012

protected access specifier in C#

In object oriented programming (OOPS) languages, access specifier plays an important role in conveying who should use what. Read my another post to know what are access specifiers, why they are needed in OOPS

Now let's understand protected access specifier by going through topics:

  1. Literal meaning of protected access specifier
  2. Significance of protected access specifier
  3. An example of protected access specifier
  4. More on private access specifier

Literal meaning of protected access specifier

When you mark a class member, property or method as protected it can only be accessed from inside the class in which it is defined and from the classes which derive from them.

Significance of protected access specifier

When a class developer has said a member is protected, he/she means that it is not meant for somebody outside the class except the class derives from it. The class author has created the protected access member by knowing that, only the class in which it is defined and the classes derive from it can access such members. Because the class in which it is defined and the derived classes will have right context to use or to provide the implementation for the protected access specifier.

So when writing a class, if you want to expose members, properties and methods to only the derived classes, consider marking those as protected.

Access specifier will tell the intention of the class author on how a class should be used. So as a class author and consumer of the class, it is your responsibility to use them properly while designing your class hierarchy.

An example of protected access specifier

More on private access specifier

  1. If you are creating a class hierarchy, mark all base class members which you think should only be accessed by derived classes.
  2. Most of the times all protected methods will be marked as virtual also. So that derived classes can override to provide a custom implementation.
  3. If your class is not going to be used a base class then don't mark any members as protected and consider marking them with private specifier.