Andrew Ducker (andrewducker) wrote,
Andrew Ducker

A new annoyance with C#

According to the C# specification:

In a virtual method invocation, the run-time type of the instance for which that invocation takes place determines the actual method implementation to invoke. In a non-virtual method invocation, the compile-time type of the instance is the determining factor. In precise terms, when a method named N is invoked with an argument list A on an instance with a compile-time type C and a run-time type R (where R is either C or a class derived from C), the invocation is processed as follows:

  • First, overload resolution is applied to C, N, and A, to select a specific method M from the set of methods declared in and inherited by C. This is described in Section
  • Then, if M is a non-virtual method, M is invoked.
  • Otherwise, M is a virtual method, and the most derived implementation of M with respect to R is invoked.

all of which boils down to - non-virtual methods take priority over virtual ones, even if the virtual ones are a better fit.

Which means that if you have two methods on a class:
virtual void DoSomething(string myString)
void DoSomething(object myObject)

and you call:
myClass.DoSomething("Hello World");

then it calls the object version rather than the string version!


  • Post a new comment


    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened