22 December 2012

Access specifier in C#

In OOPS programming, access specifiers plays an important role, to tell explicitly who should access what and who shouldn't access what.

There is a misconception that access specifiers will help us to improve the security. It’s not true. Using refection you can invoke private members of any class. So we have to aware of the fact that, access specifies are there to explicitly tell, who can access what but not to strictly enforce it.

Using access specifier we can tell, class members can be accessed only inside the defined class. This is because only the defined class knows to how to set the value or its responsibility of the defined classes to set the value for some members. Exposing these class members to the outside classes might lead to confusion in the mind of developer, can I set the value to this member even from the outside the class as well. If you know for sure a member should only be accessed from the inside the class not by anybody else, mark that member of the class as private. Then it cannot/shouldn't be accessed from outside the defined class. If a developer tries to access it, either by set or get there will be a compile time error. Visual Studio intelligence doesn't show the privately specified members when trying to access from outside the class.

Without much ado, now let begin what are the different access specifiers available in Microsoft .NET and which access specifier to use when and where.

There are 5 different access specifiers.

  1. private access specifier
  2. protected access specifier
  3. internal access specifier
  4. protected internal access specifier
  5. public access specifier

private access specifier

Marking a class member as 'private' means it cannot be accessed form outside the class.

protected access specifier

Marking a class member as 'protected' means it can only be accessed from inside the class and from the derived classes.

internal access specifier

When you said a class or its member as 'internal' it can only accessed from any classes defined in the same assembly.

protected internal access specifier

Protected internal members can only be accessed inside the same assembly and derived classes.

public access specifier

When you mark a class or a member of class, it can be accessed from anybody. So when defining public entities (for example public methods) you should ensure parameter sanity checking before using them. Check whether passed values are valid and if not throw exceptions.