CSharp examples for Custom Type:Inheritance
Cast object to sub class
using static System.Console; using System;//ww w. j ava 2s.co m using System.Collections.Generic; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { Employee aliceInEmployee = new Employee{ Name = "Alice", EmployeeCode = "1234" }; Person aliceInPerson = aliceInEmployee; aliceInEmployee.WriteToConsole(); aliceInPerson.WriteToConsole(); WriteLine(aliceInEmployee.ToString()); WriteLine(aliceInPerson.ToString()); if (aliceInPerson is Employee) { WriteLine($"{nameof(aliceInPerson)} IS an Employee"); Employee e2 = (Employee)aliceInPerson; } } } public class Employee : Person { public string EmployeeCode { get; set; } public DateTime HireDate { get; set; } public new void WriteToConsole() { WriteLine($"{Name}'s birth date is {DateOfBirth:dd/MM/yy} and hire date was {HireDate:dd/MM/yy}"); } public override string ToString() { return $"{Name}'s code is {EmployeeCode}"; } } public class Person : IComparable<Person> { public string Name; public DateTime DateOfBirth; public List<Person> Children = new List<Person>(); public int CompareTo(Person other) { return Name.CompareTo(other.Name); } // methods public void WriteToConsole() { WriteLine( $"{Name} was born on {DateOfBirth:dddd, d MMMM yyyy}"); } }