CSharp/C# Tutorial - C# Access Modifiers






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.

ModifierDescription
publicFully accessible.
internalAccessible only within containing assembly or friend assemblies.
privateAccessible only within containing type.
protectedAccessible only within containing type or subclasses.
protected internalThe union of protected and internal accessibility.




Examples

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; 
} 




Example 2

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(); 
    }
} 

Restrictions on Access Modifiers

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