Let's first make sure that I am interpreting your question correctly. You have classes defined as above. You are instantiating an instance of A
and invoking a method example
that A
inherits from the base class. You want to know if it's possible for the call this.AsAString()
in the method Letter.Example
to invoke the base implementation of AsAString
rather than the derived implementation.
First, let's understand why with example
defined as above, invoking Letter.example
via an instance of A
(e.g., new A().example
) will cause A.AsAString
to be invoked. From the specification (§7.4.4):
The function member implementation to invoke is determined:
If the compile-time type of E is an interface, the function member to invoke is the implementation of M provided by the run-time type of the instance referenced by E. This function member is determined by applying the interface mapping rules (§13.4.4) to determine the implementation of M provided by the run-time type of the instance referenced by E.
Otherwise, if M is a virtual function member, the function member to invoke is the implementation of M provided by the run-time type of the instance referenced by E. This function member is determined by applying the rules for determining the most derived implementation (§10.6.3) of M with respect to the run-time type of the instance referenced by E.
Otherwise, M is a non-virtual function member, and the function member to invoke is M itself.
So now let's consider your situation. You have an instance a
of a class A
that derives from Letter
. You have invoked a method named example
via the syntax a.example()
. This will invoke Letter.example
which has definition:
public void example() {
this.AsAString();
}
This will invoke Letter.AsAString
. But, Letter.AsAString
is declared virtual
and therefore, by the bolded rule above, the method that is invoked is A.AsAString
because this
is of type A
, A
derives from Letter
, and A
provides an override
of Letter.AsAString
.
Now, if you change the definition of A.AsAString
so that it hides the base implementation using the new
modifier
public new void AsAString() {
Console.WriteLine("A");
}
then a.example
will cause the base implementation to be used and you will see the output ???
as you desire. This is because, by the rule above, the most derived implementation of Letter.AsAString
(i.e., the most derived type in the hierarchy of A
that provides a definition of the virtual
method AsAString
) is the base implementation. The new
modifier allows A
to have a method named AsAString
with the same signature as Letter.AsAString
but it is not a virtual
method.
Please let me know if I am interpreting your question incorrectly, or if any of the above requires clarification.