Inheriting from classes
The Person
type we created earlier derived (inherited) from object
, the alias for System.Object
. Now, we will create a subclass that inherits from Person
:
- In the
PacktLibrary
project, add a new class file namedEmployee.cs
. - Modify its contents to define a class named
Employee
that derives fromPerson
, as shown in the following code:namespace Packt.Shared; public class Employee : Person { }
- In the
PeopleApp
project, inProgram.cs
, add statements to create an instance of theEmployee
class, as shown in the following code:Employee john = new() { Name = "John Jones", DateOfBirth = new(year: 1990, month: 7, day: 28) }; john.WriteToConsole();
- Run the code and view the result, as shown in the following output:
John Jones was born on a Saturday.
Note that the Employee
class has inherited all the members of Person
.
Extending classes to add functionality
Now...