Method binding to base method in external library can't handle new virtual methods "between"

Posted by Berg on Stack Overflow See other posts from Stack Overflow or by Berg
Published on 2010-03-19T11:20:24Z Indexed on 2010/03/19 11:21 UTC
Read the original article Hit count: 410

Filed under:

Lets say I have a library, version 1.0.0, with the following contents:

public class Class1
{
    public virtual void Test()
    {
        Console.WriteLine( "Library:Class1 - Test" );
        Console.WriteLine( "" );
    }
}
public class Class2 : Class1
{
}

and I reference this library in a console application with the following contents:

class Program
{
    static void Main( string[] args )
    {
        var c3 = new Class3();
        c3.Test();
        Console.ReadKey();
    }
}
public class Class3 : ClassLibrary1.Class2
{
    public override void Test()
    {
        Console.WriteLine("Console:Class3 - Test");
        base.Test();
    }
}

Running the program will output the following:

Console:Class3 - Test
Library:Class1 - Test

If I build a new version of the library, version 2.0.0, looking like this:

public class Class1
{
    public virtual void Test()
    {
        Console.WriteLine( "Library:Class1 - Test V2" );
        Console.WriteLine( "" );
    }
}

public class Class2 : Class1
{
    public override void Test()
    {
        Console.WriteLine("Library:Class2 - Test V2");
        base.Test();
    }
}

and copy this version to the bin folder containing my console program and run it, the results are:

Console:Class3 - Test
Library:Class1 - Test V2

I.e, the Class2.Test method is never executed, the base.Test call in Class3.Test seems to be bound to Class1.Test since Class2.Test didn't exist when the console program was compiled. This was very surprising to me and could be a big problem in situations where you deploy new versions of a library without recompiling applications.

Does anyone else have experience with this?

Are there any good solutions?

This makes it tempting to add empty overrides that just calls base in case I need to add some code at that level in the future...

© Stack Overflow or respective owner

Related posts about c#