Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace ExplicitCasting
- {
- class Person
- {
- protected Person instance;
- public Student ToStudent()
- {
- if (!(instance is Student))
- throw new Exception ("To return student, you have to create it before");
- return (Student)this;
- }
- public Trainer ToTrainder()
- {
- if (!(instance is Trainer))
- throw new Exception ("To return trainer, you have to create it before");
- return (Trainer)this;
- }
- }
- class Student : Person
- {
- public Student()
- {
- base.instance = this;
- }
- public void ApplyToCourse()
- {
- Console.WriteLine ("I have applied to a course");
- }
- }
- class Trainer : Person
- {
- public Trainer()
- {
- base.instance = this;
- }
- public void CreateCourse()
- {
- Console.WriteLine ("I have created a course");
- }
- }
- class MainClass
- {
- public static void Main (string[] args)
- {
- Person p;
- int type = int.Parse (Console.ReadLine());
- string cmd = Console.ReadLine();
- switch (type)
- {
- case 1:
- p = new Student();
- break;
- case 2:
- p = new Trainer();
- break;
- default:
- throw new Exception("Invalid type");
- }
- if (cmd == "apply") {
- p.ToStudent().ApplyToCourse();
- } else if (cmd == "create") {
- p.ToTrainder().CreateCourse();
- } else {
- throw new Exception ("Invalid cmd");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement