Such a class member is available in the current class and in derived classes.
Derived classes can reside in other assemblies.
Such a class member is NOT AVAILABLE for a class object.
Example 1 (2 compile-time errors)
C#
class Book
{
// class field
protected string Name;
// class method
protected string GetInfo()
{
return "Title of the book " + Name; // get the value from the class field
}
}
class Program
{
static void Main(string[] args)
{
// create a class object
Book book1 = new Book();
// set a value for the class object
book1.Name = "aaa"; // Compilation error! Book.Name is inaccessible due to its protection level
// call the method GetInfo
string str1 = book1.GetInfo(); // Compilation error! Book.GetInfo() is inaccessible due to its protection level
}
}
Example 2 (inheritance)
3 compile-time errors
C#
class Book
{
// class field
protected string Name;
// class method
protected string GetInfo()
{
return "Title of the book " + Name; // get the value from the class field
}
}
class ShowBook : Book
{
protected void Show()
{
string info = GetInfo(); // call the method GetInfo from the base class Book
Console.WriteLine(info);
}
}
class Program
{
static void Main(string[] args)
{
ShowBook book2 = new ShowBook();
// set a value for the class object
book2.Name = "aaa"; // Compilation error! Book.Name is inaccessible due to its protection level
// call the method GetInfo
string str2 = book2.GetInfo(); // Compilation error! Book.GetInfo() is inaccessible due to its protection level
// call the method Show
book2.Show(); // Compilation error! ShowBook.Show() is inaccessible due to its protection level
}
}