CSharp examples for Custom Type:Method
Catch exception thrown from method
using static System.Console; using System;/*from w w w . j av a 2s . 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()); try { aliceInEmployee.TimeTravel(new DateTime(1999, 12, 31)); aliceInEmployee.TimeTravel(new DateTime(1950, 12, 25)); } catch (PersonException ex) { WriteLine(ex.Message); } } } public class PersonException : Exception { public PersonException() : base() { } public PersonException(string message) : base(message) { } public PersonException(string message, Exception innerException) : base( message, innerException) { } } 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}"); } public override string ToString() { return $"{Name} is a {base.ToString()}"; } public void TimeTravel(DateTime when) { if (when <= DateOfBirth) { throw new PersonException("exception"); } else { WriteLine($"Welcome to {when:yyyy}!"); } } }