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
PacktLibraryproject, add a new class file namedEmployee.cs. - Modify its contents to define a class named
Employeethat derives fromPerson, as shown in the following code:using System; namespace Packt.Shared; public class Employee : Person { } - In the
PeopleAppproject, inProgram.cs, add statements to create an instance of theEmployeeclass, 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.