15

What is the difference between a run-time type and a compile-time type in C# and what implications exist regarding virtual method invocation?

asked Jun 4, 2016 at 13:47
0

1 Answer 1

24

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.

answered Jun 4, 2016 at 14:50
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Thank you for taking the time to type our a very clear answer. Much appreciated.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.