Inheriting from classes
The Person type we created earlier derived (inherited) from 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: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", Born = new(year: 1990, month: 7, day: 28, hour: 0, minute: 0, second: 0, offset: TimeSpan.Zero) }; john.WriteToConsole(); - Run the
PeopleAppproject 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.