Class Access


C# Access Modifiers

C# has 4 access modifiers, these are

A public member can be accessed by code defined outside of its class. A private member can be accessed only by methods defined within a class. Private is the default access of a class member.

Restricting access to class members is part of the object oriented programming paradigm. It allows classes to be defined as protected, self-contained units of code. A public interface, including methods, properties and events etc supply the external interface, while private methods and data protect the integrity of the internals of the class.

The protected access modifier applies to inheritance, a topic to be covered in what follows.

An access specifier precedes the rest of a member's type specification. Some examples are shown below.

class X
{
 public string s;
 public int i;
 private double d;

 private bool IsFunction(byte b) { ... }
}

An example of a class using access specifiers is shown below.

// Access - Access Modifiers

using System;

class Z
{
    private int x;
    public int y;

    public Z(int xSet, int ySet) { x = xSet; y = ySet; }

    public void SetX(int xSet) { x = xSet; }
    public void SetY(int ySet) { y = ySet; }

    public int GetX() { return x; }
    public int GetY() { return y; }
}

class Program
    {
        static void Main()
        {
            Z obj = new Z(100, 200);
            Console.WriteLine("obj = ({0},{1})", obj.GetX(), obj.GetY());

            // obj.x = 300;  // access violation if uncommented - x private
            obj.y = 400;     // access permitted - y public
        }
    }

The output of the program is as follows.

obj = (100,200)

The constructor and all four methods of class Z are defined to be public. Each of these methods access private fields. The methods actually define an interface to access the private members (x in this case). There are better ways to do this with properties. The member x is private and the member y is public. In Main(), a commented code fragment shows a disallowed operation. If this line is uncommented, a compile time error results. It is clear that a private member can be used by other members of the class but not by code outside the class.

internal Access

The internal modifier declares a member that is known throughout an assembly, but it is unknown outside that assembly. The internal modifier can be applied to classes and members of classes and to structures and members of structures. The internal modifier can also be applied to interface and enumeration declarations. The protected modifier can be used for a protected internal modifier pair (applies to class members only).

Friend Assemblies

One assembly can be made the friend of another assembly. A friend has access to the internal members of the other assembly. To declare a friend assembly, the assembly's name (and possibly its public key token) must be specified in an InternalsVisibleTo attribute.