usingSystem;//all types have derived from System.Object.Internal classEmployee/*: System.Object (This is the implicit Object)*/ {}Internal classManager:employee {} Public Static classProgram { Public Static voidMain () {//No cast needed since new returns an Employee object//And Object is a base type of Employee.Object o =NewEmployee (); //Cast required Since Employee is a derived from Object. //Other languages (such as Visual Basic) might not require//This is cast to compile.Employee e =(Employee) o; } Public Static voidMain2 () {//Construct a Manager object and pass it to PromoteEmployee. //A Manager is-a object:promoteemployee runs OK.Manager m =NewManager (); PromoteEmployee (m); //Construct a DateTime object and pass it to PromoteEmployee. //A DateTime is isn't derived from Employee. PromoteEmployee//throws a System.InvalidCastException exception.DateTime Newyears =NewDateTime ( -,1,1); PromoteEmployee (Newyears); } Public Static voidPromoteEmployee (Object o) {//at this point, the compiler doesn don't know exactly what//type of object o refers to. So the compiler allows the//code to compile. However, at run time, the CLR does know//What type O refers to ( each time the cast is performed) and//it checks whether the object World抯 type is an Employee or any type//That's derived from Employee.Employee e =(Employee) o; } Public Static voidPromoteEmployee2 (Object o) {if(O isEmployee) {Employee e=(Employee) o; //Use e within the remainder of the ' if ' statement. } } Public Static voidPromoteEmployee3 (Object o) {Employee e= O asEmployee; if(E! =NULL) { //Use e within the ' if ' statement. } } Internal classB//Base class } Internal classd:b {//Derived class } Private Static voidMain3 () {//For Table 4-3Object O1 =NewObject (); Object O2=NewB (); Object O3=NewD (); Object O4=O3; B B1=NewB (); B B2=NewD (); D D1=NewD (); //B B3 = new Object (); //D d2 = new Object ();B B4 =D1; //D d3 = B2;D D4 =(D) D1; D d5=(D) B2; D d6= (D) B1;//Throws InvalidCastExceptionb b5 = (b) O1;//Throws InvalidCastExceptionB B6 =(D) B2; }}
C # Basics--Type Basics