Compartir a través de


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 (C# Reference) and Access Modifiers (C# Programming Guide).

Example

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. Public methods named GetName and Salary are added to allow controlled access to the private members. The name member is accessed by way of a public method, and the salary member is accessed by way of a public read-only property. (See Properties (C# Programming Guide) for more information.)

class Employee2
{
    private string name = "FirstName, LastName";
    private double salary = 100.0;

    public string GetName()
    {
        return name;
    }

    public double Salary
    {
        get { return salary; }
    }
}

class PrivateTest
{
    static void Main()
    {
        Employee2 e = new Employee2();

        // The data members are inaccessible (private), so 
        // they 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;
    }
}

C# Language Specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See Also

Reference

C# Keywords

Access Modifiers (C# Reference)

Accessibility Levels (C# Reference)

Modifiers (C# Reference)

public (C# Reference)

protected (C# Reference)

internal (C# Reference)

Concepts

C# Programming Guide

Other Resources

C# Reference