private static void Demo02() { //HR.Employee e = new HR.Employee(); HR.PartTimeEmployee pt = new HR.PartTimeEmployee(); HR.ForentPEmployee ft = new HR.ForentPEmployee(); HR.Employee[] emps = { /* e, */ pt, ft }; }
private static void Demo03() { { int x1 = 10; long y = x1; int x2 = (int)y; } { HR.PartTimeEmployee pt1 = new HR.PartTimeEmployee(); HR.Employee e = pt1; #region Non Type Safe Operation // Below 2 success { // if fail throw error : System.InvalidCastException HR.PartTimeEmployee pt2 = (HR.PartTimeEmployee)e; Console.WriteLine(pt2); } { // if fail return null HR.PartTimeEmployee pt2 = e as HR.PartTimeEmployee; Console.WriteLine(pt2); } // Below 2 fail on runtime { // if fail throw error : System.InvalidCastException HR.PermanentEmployee pm = (HR.PermanentEmployee)e; Console.WriteLine(pm); } { // if fail return null HR.PermanentEmployee pm = e as HR.PermanentEmployee; Console.WriteLine(pm); } #endregion #region Type Safe Operation { if (e is HR.PermanentEmployee) { HR.PermanentEmployee pm = (HR.PermanentEmployee)e; Console.WriteLine(pm); } } { // if fail return null HR.PermanentEmployee pm = e as HR.PermanentEmployee; if (pm != null) { Console.WriteLine(pm); } } #endregion } }