Access Specifiers
In this chapter you will learn:
- Get to know C#'s Access Specifiers
- Matrix showing the usage of access modifiers
- A demo showing how to use access modifiers
C#'s Access Specifiers
An access specifier determines how other parts of a program can access a class member.
Member access is controled by four access specifiers:
Access modifier | Meaning |
---|---|
public | Accessible anywhere; |
internal | Accessible only within its assembly or friend assemblies; |
private | Visible only within its own type; |
protected | Visible only within containing type or subclasses |
protected internal | The union of protected and internal accessibility |
interal
is the default for non-nested types.
public
is implicit for members of an enum or interface type.
private
is the default for members of a class or struct.
Matrix showing the usage of access modifiers
Visibility modifiers indicate which other code items can view an item.
Modifier | Applies To | Description |
---|---|---|
public | Any types or members | visible to all . |
protected | Any member of a type, also any nested type | visible only to all derived type. |
internal | Any member of a type, also any nested type | visible only within its containing assembly. |
private | Any types or members | visible only inside the type to which it belongs. |
protected internal | Any member of a type, also any nested type | visible to any code within its containing assembly and also to any code inside a derived type. |
Demo for access modifiers
class MyClass/* j av a2 s. c o m*/
{
public string publicStringField;
protected internal string protectedInternalStringField;
internal string internalStringField;
protected int protectedField = 150;
private int privateField;
public void setPrivateField(int privateField)
{
this.privateField = privateField;
}
public int getPrivateField()
{
return privateField;
}
public void Start()
{
System.Console.WriteLine("Starting MyClass ...");
privateMethod();
System.Console.WriteLine("MyClass started");
}
private void privateMethod()
{
System.Console.WriteLine("Turning starter motor ...");
}
}
class MainClass
{
public static void Main()
{
MyClass myMyClass = new MyClass();
myMyClass.publicStringField = "Toyota";
myMyClass.protectedInternalStringField = "MR2";
myMyClass.internalStringField = "black";
myMyClass.setPrivateField(1995);
System.Console.WriteLine("myMyClass.publicStringField = " + myMyClass.publicStringField);
System.Console.WriteLine("myMyClass.protectedInternalStringField = " + myMyClass.protectedInternalStringField);
System.Console.WriteLine("myMyClass.internalStringField = " + myMyClass.internalStringField);
System.Console.WriteLine("myMyClass.getPrivateField() = " + myMyClass.getPrivateField());
myMyClass.Start();
}
}
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
Home » C# Tutorial » Class