Access Modifiers - CSharp Custom Type

CSharp examples for Custom Type:access level

Introduction

For encapsulation, a type or type member may limit its accessibility to others by adding one of five access modifiers to the declaration:

Modifiers Meaning
public Fully accessible. This is the implicit accessibility for members of an enum or interface.
internal Accessible only within the containing assembly or friend assemblies. This is the default accessibility for non-nested types.
private Accessible only within the containing type. This is the default accessibility for members of a class or struct.
protected Accessible only within the containing type or subclasses.
protected internalThe union of protected and internal accessibility.

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

Functions within Subclass can call Bar but not Foo:

class BaseClass                                                                                
{                                                                                             
  void Foo()           {}        // Foo is private (default)                                  
  protected void Bar() {}                                                                     
}                                                                                             
class Subclass : BaseClass
{
  void Test1() { Foo(); }       // Error - cannot access Foo
  void Test2() { Bar(); }       // OK
}

Related Tutorials