Visibility and Accessibility Modifiers

Private Access Modifier

The modifier keyword private is used to restrict access to type members, or can be applied to nested classes, them being classes nested within other classes.
using System; public class Program...

 

It cannot be applied to classes unless they are "nested classes". You cannot apply the private modifier to classes directly in namespaces. The private modifier is also the default access modifier that is applied when you omit any access modifier from your code, for example, the following:

public class Program
{
    private class PrivateClass
    {

    }
}

This class declaration is equivalent:

public class Program
{
    class PrivateClass
    {

    }
}

It is a best practice to make sure you use the private access modifier instead of omitting it, because although they are equivalent declarations, it helps other developers understand the intentions of your code.

Like the public keyword, the context in which the modifier is applied matters.

From the context of a type, no external callers outside of the parent public class that declares your type has access to it.

From the context of a type member, no external callers, including those in the same program assembly will be able to access the type member. This essentially means private code is only accessible from the type in which the member is declared.

Here is another example showing how private can even be used to prevent access from a subclassed (inherited type):

public class Message
{
    private string Address { get; set; }    
}

public class Email : Message
{
    public string GetAddress()
    {
        return base.Address; // Can't access private Property.
    }
}

The private modifier is also important in terms of constructors. Take a look at the following example:

public class Person
{
    private Person()
    {
        // Private constructor
    }
}

The above declaration is a public class, with a private constructor. This arrangement allows external callers to have references to the class Program, but they won't be able to create instances. For example, in another part of your program, if you try and do this:

Person person new Person();

This is a compile error, because the constructor for that type is marked as private.

Page 4 of 18