23 December 2012

private access specifier in C#

In OOPS programming access specifier plays an important role to restrict access to members of the class otherwise could result in corrupting the state of the application. Read my another post to know about what are access specifiers in C# .NET & why they need in OOPS.

Let's go through the below sections to know about private access specifier.

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

Literal meaning of private access specifier

When you mark a class member, property or method as private, it cannot be accessed from the except the class in which it's defined. A private member of class can be accessed inside the class in which it present.

Significance of private access specifier

When a class developer has said a member as private, he/she means that it not meant for somebody outside the class. He has maintained the private access member to maintain internal logic or internal state of the class. So as consumer of the class, you are least bothered about internal details of the class and also when you don't know internal details of the class, accessing such members of class by GET or SET will lead to unexpected class behavior and hence the reason, the class developer has marked the member with private access specifier.

So when are writing a class, if you don't want to expose any member, property and methods to the outside the class mark them with private access specifier.

An example of private access specifier

As a consumer of Employee class you are least bothered about which class is formatting the employee object to a string representation.So the Employee class developer has rightly marked EmployeeDescriptionGenerator member with private access specifier.

More on private access specifier

  1. By default All member variables in a class are private. If we don't specify any access specifier for members in a class they are private.
  2. Constructors, methods, properties are private by default.
  3. Abstract or virtual members cannot be private
  4. You cannot specify any access specifier for destructors in a class. It makes sense as destructors are called by .NET Garbage collection. Allowing them to mark as private doesn't make sense. C# compiler will check for this and compilation will fail in case we try to mark destructors with any access specifier.
  5. Not but not the least, your class members should always be designed with lower access specifier i.e. private access specifier. On need basis only you should increase their access level.