Defining Member and Type Visibility - Protected Members
(Page 4 of 6 )
Another access modifier supported in C# is protected. A protected member is accessible within its class and by derived classes. Derived classes are classes that inherit the functionality of classes higher in the hierarchy. For example, a son inherits some of the characteristics of his father, a circle inherits some of the characteristics of a shape, and so on…
In the case of managers and employees, we know that a manager is, after all, an employee. So it makes sense to create data members inside the Employee class that only the Manager class can access (or any other class that inherits from Employee (like SalesPerson)). Here is an illustration:
class Program
{
static void Main(string[] args)
{
Manager m = new Manager("Tim", 12345, 1500);
m.PrintInfo();
}
}
class Employee
{
protected string name;
protected int id;
public Employee(string e_name, int e_id)
{
name = e_name;
id = e_id;
}
}
class Manager : Employee
{
private double bonus;
public Manager(string m_name, int m_id, double m_bonus)
: base(m_name, m_id)
{
bonus = m_bonus;
}
public void PrintInfo()
{
Console.WriteLine("Manager " + name +
" with id " + id + " has bonus " + bonus);
}
}
Notice that name and id in the Employee class were successfully accessed from the Manager class because they were declared protected in the Employee class. And Manager inherits from Employee (C# uses the semicolon (:) to illustrate inheritance). In the Manager constructor, we used the base keyword to access the Employee’s constructor in order to initialize name and id.
Next: Internal and Protected Internal Members >>
More C# Articles
More By Ayad Boudiab