Reputation: 406
What is the difference between a run-time type and a compile-time type in C# and what implications exist regarding virtual method invocation?
Upvotes: 15
Views: 4489
Reputation: 3733
Lets say we have two classes A
and B
declared as follows:
internal class A
{
internal virtual void Test() => Console.WriteLine("A.Test()");
}
internal class B : A
{
internal override void Test() => Console.WriteLine("B.Test()");
}
B
inherits from A
and overrides the method Test
which prints a message to the console.
What is the difference between a run-time type and a compile-time type in C#
Now lets consider the following statement:
A test = new B();
at compile time: the compiler only knows that the variable test
is of the type A
. He does not know that we are actually giving him an instance of B
. Therefore the compile-type of test
is A
.
at run time: the type of test
is known to be B
and therefore has the run time type of B
and what implications exist regarding virtual method invocation
Consider the following code statement:
((A)new B()).Test();
We are creating an instance of B
casting it into the type A
and invoking the Test()
method on that object. The compiler type is A
and the runtime type is B
.
When the compiler wants to resolve the .Test()
call he has a problem. Because A.Test()
is virtual
the compiler can not simply call A.Test
because the instance stored might have overridden the method.
The compile itself can not determine which of the methods to call A.Test()
or B.Test()
. The method which is getting invoked is determined by the runtime and not "hardcoded" by the compiler.
Upvotes: 24