This is a beginner’s question, but I am interested in learning what’s going on here. My question is, what goes on behind the scenes when you down-cast an object? Does it maintain some sort of metadata about what it originally was? Here’s what I mean:
Suppose I have a method called “ClockIn” that accepts a parameter of type “Employee”:
public static void ClockIn(Employee employee)
{
var manager = employee as Manager;
if (manager != null)
{
manager.OpenSafe();
}
}
So, assume that Manager is a subclass of the Employee type and that it has the “OpenSafe” method:
public class Manager : Employee
{
public void OpenSafe()
{
...
}
}
The “ClockIn” method, if it finds that a Manager has been passed in, calls the OpenSafe method. Such as:
var bob = new Manager();
ClockIn(bob);
Here, I’ve passed in an instance of type Manager into a method that accepts the base class Employee. I need to cast the instance inside the ClockIn method to Manager before I can call OpenSafe.
The question is, is there some metadata that remembers that “bob” is a Manager, even though I’ve passed him in as an Employee? How does the code know that he can indeed be cast to a Manager? Is there something going on in the heap?
The first thing to remember is that casting does not change the original object at all. It only changes your view of the object through that particular reference. More than one reference can be pointing to the same object, so changing the object isn’t a reasonable thing to do on a cast.
What you might do in your instance is to make
ClockIn()a method of theEmployeeclass. Then, when you callthen
bobwill know what type he really is, and call the appropriateClockIn()method for his type. This is called dynamic method dispatch and is not available forstaticfunctions as in your example.For example: