C# Keywords Tutorial Part 65: private

C# Keywords Tutorial Part 65: private

Encapsulation, inheritance, and polymorphism are all features supported by the object-oriented programming language C#. Controlling access to class members, such as fields, properties, and methods, is one of encapsulation’s primary advantages. In C#, access modifiers may be used to manage a class’s members’ visibility. One of the access modifiers in C# that limits a member’s accessibility to the contained class alone is the “private” keyword.

Using the “private” keyword

A class member is designated as private with the term “private”. An outsider cannot access a private member; only members of the same class may do so. The derived classes and any other classes aside from the contained class are not able to see private members. Here is an illustration of a C# private member variable:

public class Employee
{
? ? private string empName;
? ? private int empAge;
}        

In this example, the Employee class has two private member variables, empName and empAge. These variables can only be accessed within the Employee class and not from any other class. To access these variables, you need to use public methods or properties that provide the necessary access to them.

Private members in action

Here is an example that demonstrates the use of private members in C#:

public class Employee
{
? ? private string empName;
? ? private int empAge;


? ? public Employee(string name, int age)
? ? {
? ? ? ? empName = name;
? ? ? ? empAge = age;
? ? }


? ? public void DisplayEmployeeInfo()
? ? {
? ? ? ? Console.WriteLine("Employee Name: {0}", empName);
? ? ? ? Console.WriteLine("Employee Age: {0}", empAge);
? ? }
}        

In this example, the Employee class has two private member variables, empName and empAge. These variables are initialized using a public constructor that takes two parameters, name and age. The DisplayEmployeeInfo() method is a public method that displays the employee information using the Console.WriteLine() method.

Here is an example of how you can create an instance of the Employee class and call the DisplayEmployeeInfo() method:

Employee emp = new Employee("John Doe", 35);
emp.DisplayEmployeeInfo();        

In this example, a new instance of the Employee class is created using the new keyword and the constructor parameters are passed to it. The DisplayEmployeeInfo() method is then called on the emp object, which displays the employee information on the console.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了