Export (0) Print
Expand All

private

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.

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.

Example

In this example, the Employee class contains a public member, Name, and a private member, Salary. The public member can be accessed directly, while the private member must be accessed through the public method AccessSalary().

// private_keyword.cs
using System;
class Employee 
{
   public string name = "xx";
   double salary = 100.00;   // private access by default
   public double AccessSalary() {
      return salary;
   }
}

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

      // Accessing the public field:
      string n = e.name; 
      
      // Accessing the private field:
      double s = e.AccessSalary();    
   }
}

In the preceding example, if you attempt to access the private members directly by using a statement like this:

double s = e.salary;

you will get the error message:

'Employee.Salary' is inaccessible due to its protection level.

See Also

C# Keywords | Access Modifiers | Accessibility Levels | Modifiers | 3.5.1 Declared accessibility

Show:
© 2014 Microsoft