Friday, October 22, 2010

Understanding The private access specifier in c Sharp.

The private access specifier allows a class to hide its member variables and member function from other class objects and functions. Therefore, the private member of a class is not visible outside a class. If a member is declared private, only the functions of that class can access the member. Even the instance of the class cannot access its private members. Therefore, the data is hidden and cannot be altered by any function other than the member functions of the class.

The following is an example of the use of private access specifier।

using System;
class Car
private string Model;
void Honk()
System.Console.WriteLine("PARRP PARRP!");
public void SetModel()
System.Console.WriteLine("Enter the model name: ");
Model = System.Console.ReadLine();
public void DisplayModel()
System.Console.WriteLine("The model is: {0}", Model);

class Display
static void Main(string[] args)
Car Ford = new Car();
Ford।SetModel(); //Accepts the Model name
Ford.DisplayModel(); //displays the model name

Ford.Honk(); //error! private member cannot be accessd outside the class defination.

System।Console.WriteLine(Ford.Model); //error! private members cannot be accessed outside the class defination


Note: -The SetModel () and DisplayModel () functions can be called from the Ford object, created in the Main () function because these are public member function. Similarly, the Honk () function cannot be accessed through the Ford object because it is a private member function.

C Sharp Access specifier Related Contents.

Understanding the public Access specifier in c#:
Understanding The protected access specifier in c Sharp.
Understanding The internal access specifier in c Sharp.
understanding the protected internal Access Specifier in c#:
if...else construct in c sharp.

No comments:

Recent Posts