Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

private (C# Reference)

The private keyword is a member access modifier. Private access is the least permissive access level. Private members are accessible only within the body of the class or the struct in which they are declared, as in this example:

class Employee
    private int i;
    double d;   // private access by default

Nested types in the same body can also access those private members.

It is a compile-time error to reference a private member outside the class or the struct in which it is declared.

For a comparison of private with the other access modifiers, see Accessibility Levels and Access Modifiers (C# Programming Guide).

In this example, the Employee class contains two private data members, name and salary. As private members, they cannot be accessed except by member methods, so public methods called GetName and Salary are added to allow controlled access to the private members. The name member is accessed via public method, and the salary member is accessed via a public read-only property. (See Properties (C# Programming Guide) for more information.)

// private_keyword.cs
using System;
class Employee
    private string name = "FirstName, LastName";
    private double salary = 100.0;

    public string GetName()
        return name;

    public double Salary
        get { return salary; }

class MainClass
    static void Main()
        Employee e = new Employee();

        // The data members are inaccessible (private), so
        // then can't be accessed like this:
        //    string n = e.name;
        //    double s = e.salary;

        // 'name' is indirectly accessed via method:
        string n = e.GetName();

        // 'salary' is indirectly accessed via property
        double s = e.Salary;

For more information, see the following sections in the C# Language Specification:

  • 3.5.1 Declared Accessibility

  • 3.5.4 Accessibility constraints

  • 10.2.3 Access Modifiers

  • Declared Accessibility

  • Access to private and protected members of the containing type

Community Additions

© 2015 Microsoft