Friday, October 22, 2010

Understanding The protected access specifier in c Sharp.

The protected access specifier allows a class to hide its member variables and member functions from other class objects and functions, except the child class। The protected access specifier becomes important while implementing inheritance.

The following example shows that the protected member of the class will have the same visibility as a private member of the class:

using System;
class Car
protected 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! protected members cannot be accessed*/


Note: -The SetModel () and DisplayModel () functions can be called from the Ford object, defined in the Main () function. However, the Model variable cannot be accessed through the Ford object because it is a protected member variable. Similarly, the Honk () function cannot be access through the Ford object because it is also a private member function.

C Sharp Access specifier Related Contents.

Understanding the public Access specifier in c#:
Understanding The private 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