Cast to sub class with as - CSharp Custom Type

CSharp examples for Custom Type:as

Description

Cast to sub class with as

Demo Code

using static System.Console;
using System;/*from  w ww. j a  v  a  2 s  .  c  om*/
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());
      Employee e3 = aliceInPerson as Employee;
      if (e3 != null)
      {
         WriteLine($"{nameof(aliceInPerson)} AS an Employee");
      }
   }
}
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);
   }
   public void WriteToConsole()
   {
      WriteLine($"{Name} was born on {DateOfBirth:dddd, d MMMM yyyy}");
   }
}

Result


Related Tutorials