C#: Access modifiers for classes

This entry is part 17 of 71 in the series C#

In the earlier examples, we have used public and private to declare displayName() method.

There are basically 4 access modifiers in C#, public, private, protected and internal.

When we declare a function as public, access to it will not be restricted.

Declared AccessibilityMeaning
publicAccess is not restricted.
protectedAccess is limited to the containing class or types derived from the containing class.
internalAccess is limited to the current assembly.
protected internalAccess is limited to the current assembly or types derived from the containing class.
privateAccess is limited to the containing type.

Note that access modifiers are not applicable to namespaces.

Internal classes are accessible only within files in the same assembly.

For example, the code below will not produce an error since it will be assembled in one source or cs file.

using System;

namespace Hello
    class Friend
        internal void displayName(String name)
            Console.WriteLine("Hello, what is your name?");
            Console.WriteLine("Your name is " + name);

        static void Main()
            string name = "John";

            Friend friend = new Friend();           

If we have one source file Assembly1.cs during the first assembly and we produce another source file Assembly2.cs during a second assembly, the first file contains an internal base class, BaseClass. In the second file, an attempt to instantiate BaseClass will produce an error.

For more information about internal member functions or types, you can also refer to msdn here.


Series Navigation<< C#: Passing an argument or a variable into a method
C#: The core ideas of Object-Oriented Programs >>