I master C # and got a little confused with the cast mechanism.

internal class Employee{ } internal class ExtendedEmployee : Employee{ } class Program { static void Main(string[] args) { ExtendedEmployee exE = new ExtendedEmployee(); Employee e = exE as Employee; Console.WriteLine(e.GetType()); } } 

Logically, it should return the type Employee , however, it deduces that the type is ExtendedEmployee . What did I understand wrong? Explicit cast ( Employee ) too

  • If you are satisfied with the answer received, please accept it - daw next to the answer - ixSci

1 answer 1

The GetType() function returns the real, dynamic type of an object by reference. You are not interested in the static type: you already know it.

The exE as Employee expression does not change the object itself, only the static type of the link changes. Both references e and exE point to the same object of the dynamic type ExtendedEmployee .

  • Thank you, I caught the essence. - Valter Scott
  • @ValterScott: Please! - VladD