Advertisement
Guest User

ExplicitCastingExample

a guest
Dec 29th, 2014
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.38 KB | None | 0 0
  1. using System;
  2.  
  3. namespace ExplicitCasting
  4. {
  5.     class Person
  6.     {
  7.         protected Person instance;
  8.  
  9.         public Student ToStudent()
  10.         {
  11.             if (!(instance is Student))
  12.                 throw new Exception ("To return student, you have to create it before");
  13.  
  14.             return (Student)this;
  15.         }
  16.  
  17.         public Trainer ToTrainder()
  18.         {
  19.             if (!(instance is Trainer))
  20.                 throw new Exception ("To return trainer, you have to create it before");
  21.  
  22.             return (Trainer)this;
  23.         }
  24.     }
  25.  
  26.     class Student : Person
  27.     {
  28.         public Student()
  29.         {
  30.             base.instance = this;
  31.         }
  32.  
  33.         public void ApplyToCourse()
  34.         {
  35.             Console.WriteLine ("I have applied to a course");
  36.         }
  37.     }
  38.  
  39.     class Trainer : Person
  40.     {
  41.         public Trainer()
  42.         {
  43.             base.instance = this;
  44.         }
  45.  
  46.         public void CreateCourse()
  47.         {
  48.             Console.WriteLine ("I have created a course");
  49.         }
  50.     }
  51.  
  52.  
  53.     class MainClass
  54.     {
  55.         public static void Main (string[] args)
  56.         {
  57.             Person p;
  58.  
  59.             int type = int.Parse (Console.ReadLine());
  60.             string cmd = Console.ReadLine();
  61.  
  62.             switch (type)
  63.             {
  64.                 case 1:
  65.                     p = new Student();
  66.                     break;
  67.                 case 2:
  68.                     p = new Trainer();
  69.                     break;
  70.                 default:
  71.                     throw new Exception("Invalid type");
  72.             }
  73.  
  74.             if (cmd == "apply") {
  75.                 p.ToStudent().ApplyToCourse();
  76.             } else if (cmd == "create") {
  77.                 p.ToTrainder().CreateCourse();
  78.             } else {
  79.                 throw new Exception ("Invalid cmd");
  80.             }
  81.         }
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement