A type or type member may limit its accessibility to other types by using access modifiers.
For example, we can set the access level to a method so that it only be access inside the type where it is defined. In that way we know that the method is not used and would be used anywhere else.
Here is the list of the access modifiers.
Modifier | Description |
---|---|
public | Fully accessible. |
internal | Accessible only within containing assembly or friend assemblies. |
private | Accessible only within containing type. |
protected | Accessible only within containing type or subclasses. |
protected internal | The union of protected and internal accessibility. |
In the following code, Class2 is accessible from outside its assembly; Class1 is not:
class Class1 {} // Class1 is internal (default) public class Class2 {}
In the following code, Class2 exposes field x to other types in the same assembly; Class1 does not:
class Class1 { int x; } // x is private (default) class Class2 { internal int x; }
Functions within Subclass can call methodA but not methodB:
class BaseClass { void methodB() {} // methodB is private (default) protected void methodA() {} } class Subclass : BaseClass { void Test1() { methodB(); // Error - cannot access methodB } void Test2() { methodA(); } }
When overriding a base class function, accessibility must be identical on the overridden function.
For example:
class BaseClass { protected virtual void methodB() {} } class Subclass1 : BaseClass { protected override void methodB() {} } // OK class Subclass2 : BaseClass { public override void methodB() {} } // Error