C# Access Modifiers

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  w  ww.  j a v a  2  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; }
    }
}




















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor