Home

C#Keywords: protected

     

Introduction

To maintain a privileged relationship with its children, a parent class can make a member available only to classes derived from it. With this relationship, some members of a parent class have a protected access level. Of course, as the class creator, it is your job to specify this relationship.

To create a member that only derived classes can access, type the protected keyword to its left. Here are examples:

Source File: Persons.cs
using System;

public class Person
{
	private string _name;
	private string _gdr;

	public Person(string name = "Not Available",
		      string gender = "Unknown")
	{
		this._name = name;
		this._gdr  = gender;
	}

	protected string FullName
	{
		get { return _name; }
		set { _name = value; }
	}

	protected string Gender
	{
		get { return _gdr; }
		set { _gdr = value; }
	}
		
	public void Show()
	{
		Console.WriteLine("Full Name: {0}", this.FullName);
		Console.WriteLine("Gender:    {0}", this.Gender);
	}
}

You can access protected members only in derived classes. Therefore, if you instantiate a class outside, you can call only public members:

Source File: Exercise.cs
using System;

class Exercise
{
    public static int Main()
    {
	People.Person man = new People.Person("Herman Sandt", "Male");

	Console.WriteLine("Staff Member");
	man.Show();

	Console.WriteLine();
	return 0;
    }
}

This would produce:

Staff Member
Full Name: Herman Sandt
Gender:    Male

If you create a member of a class and mark it as protected, the classes derived from its parent class, created in the current program or outside the current program, can access it. If you want the member to be accessed only by derived classes implemented in the same program but not the derived classes implemented outside of the current program, mark the member as protected internal. Here are examples:

Source File: Persons.cs
using System;

public class Person
{
	private string _name;
	private string _gdr;

	public Person(string name = "Not Available",
	 	      string gender = "Unknown")
	{
		this._name = name;
		this._gdr  = gender;
	}

	protected internal string FullName
	{
		get { return _name; }
		set { _name = value; }
	}

	protected internal string Gender
	{
		get { return _gdr; }
		set { _gdr = value; }
	}
		
	public void Show()
	{
		Console.WriteLine("Full Name: {0}", this.FullName);
		Console.WriteLine("Gender:    {0}", this.Gender);
	}
}
 
 

Home Copyright © 2010-2011 FunctionX