A method called actually calling itself recursively

I read the CLR through C # and I read the following:

Sometimes the compiler will use a call statement to invoke a virtual method instead of using the callvirt command. This may seem unexpected at first, but the code below shows why it is sometimes required:

internal class SomeClass {
// ToString is a virtual method defined in the base class: Object.
public override String ToString() {
// Compiler uses the โ€˜callโ€™ IL instruction to call
// Objectโ€™s ToString method nonvirtually.
// If the compiler were to use โ€˜callvirtโ€™ instead of โ€˜callโ€™, this
// method would call itself recursively until the stack overflowed.
return base.ToString();
}
}

When calling base.ToString (virtual method), the C # compiler emits a call command to ensure that the ToString method in the base type is called non-virtual. This is necessary because if ToString is called practically, the call will be executed recursively until the stack thread is full, which is clearly not desirable.

Although this is explained here, I do not understand why the ToString actually called will execute recursively. Can someone give another explanation or describe it in a simpler way, if possible.

Thanks!

+4
source share
1 answer

c base.ToString()do you really want to call the base class method of the ToString () method.

If you just call the method this.ToString(), it is called "virtually", i.e. called the ToString()actual class.

, base.ToString() "", , this.ToString(), ToString(), ToString() , , .

+5

Source: https://habr.com/ru/post/1617912/


All Articles