tags:

views:

127

answers:

2
class Base
{
    public virtual void MethodA(int x)
    {
        Console.WriteLine ("In Base Class");
    }
}

class Derived : Base
{
    public override void MethodA(int x)
    {
        Console.WriteLine ("In derived INT)");
    }

    public void MethodA(object o)
    {
        Console.WriteLine ("In derived OBJECT");
    }
}

class Test
{
    static void Main()
    {
        Derived d = new Derived();
        int k = 20;
        d.MethodA(k);
    }
}

The oupt put I got for this is "In derived OBJECT". What is the reason for this strange behavior. After some search I got to know the reason being the signatures declared in base class are ignored. Why are they ignored?

Thanks,

+2  A: 

The compiler in VC# 2008 checks the available non-virtual functions before virtual ones, when deciding what to call. Since your Derived class has a non-virtual MethodA(object) that can be called, the compiler calls it.

If you add a virtual MethodA(object) to Base, then Derived.MethodA(int) will get called, because then both MethodA(object) and MethodA(int) are virtuals.

I'm not familiar enough with the C# language spec to know whether this is specified behavior, or a bug in the compiler.

mjfgates
It is indeed in the ECMA spec, non-virtual will be invoked first. Also note that the method that gets called is determined by the compiler for non-virtual methods, and by the runtime type for virtual methods.
Sander Rijken
I checked this, but beware that Derived.MethodA(int) will only get called when you add the keyword 'override' to Derived.MethodA(object) (that was meant of course). Without it the optional keyword 'new' is assumed and Derived.MethodA(object) will still get called.
Gerard
+4  A: 

This is by design and for a good reason. This design helps prevent the Brittle Base Class problem. C# was designed to make it easier and safer to write "versioned" components, and this rule is a big part of that.

This is a very frequently asked question. This is one of the most common "false bug reports" that we get; that is, someone believes they have found a bug in the compiler when in fact they have found a feature.

For a description of the feature and why it is designed the way it is, see my article on the subject:

http://blogs.msdn.com/b/ericlippert/archive/2007/09/04/future-breaking-changes-part-three.aspx

For more articles on the subject of how various languages deal with the Brittle Base Class problem see my archive of articles on the subject:

http://blogs.msdn.com/b/ericlippert/archive/tags/brittle+base+classes/

Eric Lippert