Access Modifiers

MSDN C# Programming Guide

Access modifiers control access to class instance variables and class methods. The default access for class instance variables (fields) and methods in C# is private, if none is specified as part of a declaration / definition then the access is private, this restricts access from outside the class definition. Public access modifier allows access from within any other class definition, it is the least restricted and should be used sparingly when applied to class variables. public access for variables does not enforce encapsulation, it can allow unintentional modification of variable values. Public access for class methods is standard practice, It supports allowing objects to execute their class-defined methods from within another class. This is considered the mechanism that allows objects to communicate with each other. Protected access modifier allows child classes to access a base-class variable as if it were public, but outside the base and child classes, the variable access is restricted as if access were specified as private.

C# Access modifiers:

private //default - variable can only be used within the class definition
public // allows use outside the class definition
protected // can be used in a base class to allow access in child class. Outside base and child classes, the variable is private

Last updated