What is the difference between a run-time type and a compile-time type in C# and what implications exist regarding virtual method invocation?
Compile-time is the time at which the source code is converted into an executable code while the run time is the time at which the executable code is started running. Both the compile-time and runtime refer to different types of error.
A compile-time error generally refers to the errors that correspond to the semantics or syntax. A runtime error refers to the error that we encounter during the code execution during runtime. We can easily fix a compile-time error during the development of code. A compiler cannot identify a runtime error.
Execution Time is the time that your program takes to execute. For example, 10 seconds, or 10 milliseconds. Running time might be used interchangeably with execution time (how much time it takes for your program to terminate).
The declared type or compile-time type of a variable is the type that is used in the declaration. The run-time type or actual type is the class that actually creates the object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With