C# Access Modifiers
In this chapter you will learn:
Description
A type or type member may limit its accessibility to other types and other assemblies by adding one of five access modifiers to the declaration:
- public - Fully accessible.
- internal - Accessible only within containing assembly or friend assemblies
- private - Visible only within containing type
- protected - Visible only within containing type or subclasses
- protected internal - The union of protected and internal accessibility
Example
Class2 is accessible from outside its assembly; Class1 is not:
class Class1 {} // Class1 is internal (default)
public class Class2 {}
ClassB exposes field x to other types in the same assembly; ClassA does not:
class ClassA { int x; } // x is private (default)
class ClassB { internal int x; }
Note
Class members including nested classes and structs can be declared with any of the five types of access.
Struct members cannot be declared as protected because structs do not support inheritance.
User-defined operators must always be declared as public. Destructors cannot have accessibility modifiers.
The following code adds the Access Modifiers to the class
// public class://from www . ja v a2 s. com
public class Rectangle
{
// protected method:
protected void calculate() { }
// private field:
private int width = 3;
// protected internal property:
protected internal int Width
{
get { return width; }
}
}
Next chapter...
What you will learn in the next chapter:
- Use Properties to get and set private member variable
- private static and const Fields
- Using Methods to change private fields