Search⌘ K
AI Features

Additional Topics on Inheritance

Explore how inheritance works in C#, focusing on member accessibility, including private, protected, and public modifiers. Understand how constructors in base and derived classes interact, and learn techniques for calling base class constructors explicitly or implicitly to manage object initialization.

Inheritance is a powerful feature, but it comes with specific rules regarding member visibility and object initialization. This lesson explores which members are accessible to derived classes and how constructors are executed in an inheritance hierarchy.

Access the base class members

Inheritance facilitates code reuse, but we must determine exactly which members are inherited. We can answer this by trying to access base class members. Let’s consider an example:

public class EducationalOrganization
{
private string _name;
public string Name
{
get { return _name; }
}
}
public class School : EducationalOrganization
{
}
An example of inheritance structure
  • Lines 1–8: We define a base class EducationalOrganization with a private field and a public property.

  • Lines 10–12: We define a derived class School that inherits from EducationalOrganization.

The School class inherits from EducationalOrganization. We might assume that School inherits all members of EducationalOrganization, including the _name field.

First, let’s define the base class with a private field.

C# 14.0
namespace Inheritance;
public class EducationalOrganization
{
// Update this field as protected for derived classes to access it
private string _name; // This field is kept private, so derived classes cannot access it directly
public string Name
{
get { return _name; }
}
}
  • Line 3: We define the EducationalOrganization class.

  • Line 6: We declare a private field _name.

  • Lines 8–11: We provide a public property Name to expose the value of the private field.

Next, we define the derived class that inherits from this organization.

C# 14.0
namespace Inheritance;
public class School : EducationalOrganization
{
}
...