override ToString method - CSharp Custom Type

CSharp examples for Custom Type:Method

Description

override ToString method

Demo Code

using static System.Console;
using System;/*from w ww .  jav a  2  s.  c  o m*/
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
   static void Main(string[] args)
   {
      Employee e1 = new Employee
      {
         Name = "D",
         DateOfBirth = new DateTime(1990, 7, 28)
      };
      WriteLine(e1.ToString());
   }
}
public class Employee : Person
{
   public string EmployeeCode { get; set; }
   public DateTime HireDate { get; set; }
   public  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);
   }
}

Result


Related Tutorials