using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Apps
{
class Doctor1
{
protected string name, specialization;
public Doctor1(string name, string specialization)
{
this.name = name;
this.specialization = specialization;
}
public void Print()
{
Console.WriteLine(name);
Console.WriteLine(specialization);
}
}
class ResidentalDoctors1 : Doctor1
{
protected int salary;
public ResidentalDoctors1(string name, string specialization, int salary)
: base(name, specialization)
{
this.salary = salary;
}
public new void Print()
{
base.Print();
Console.WriteLine(salary);
}
public int GetPay()
{
return salary;
}
}
class Consultant1 : Doctor1
{
protected int fees, visitNum;
public Consultant1(string name, string specialization, int fees, int visitNum)
: base(name, specialization)
{
this.fees = fees;
this.visitNum = visitNum;
}
public new void Print()
{
base.Print();
Console.WriteLine(fees);
Console.WriteLine(visitNum);
}
public int GetPay()
{
return fees * visitNum;
}
}
class UnderstandingISandASoperator
{
public static void Main()
{
//The below
three lines of code will lead to exception i.e known at runtime. Since d
reference is pointing to consultant, but it is assigned to c
(ResidentalDoctors1 object)
Doctor1 d
= new Consultant1("Chitti", "General", 300,
10); // Upcasting
ResidentalDoctors1 c;
c = (ResidentalDoctors1)d; // Downcasting leads to exception. Not safe
way to do this casting.
// To overcome above problem we will see 2 ways
to resolve this
// 1. Example
Doctor1 rd
= new Consultant1("Steve", "General", 100,
100);
ResidentalDoctors1 c;
if (rd is ResidentalDoctors1) // using is operator we are handling to avoid
exception.
{
// Below statements are executed only if rd is
object reference to ResidentalDoctors1
c =
(ResidentalDoctors1)rd; //
Downcasting leads to exception
Console.WriteLine("rd
is a object reference to ResidentalDoctors1 class");
}
// 2. Example
Doctor1 rd2
= new Consultant1("Steve", "General", 100,
100);
ResidentalDoctors1 c2;
c2 =
rd2 as ResidentalDoctors1;
// Here there is
no condition and to check unlike is operator but as operator will handle
exception internally and assigns null to it if thrown.
Console.WriteLine(c2);
// This example
below will complete the casting as c3 is referring to Consultant1 and rd3 is
downcasted to Consultant1.
Doctor1 cd3
= new Consultant1("Steve", "General", 100,
100);
Consultant1 c3;
c3 =
cd3 as Consultant1;
Console.WriteLine(c3);
}
}
}