Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are signatures declared in the base class ignored?

Tags:

c#

inheritance

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 output I got for this is "In derived OBJECT". What is the reason for this strange behaviour? After some research, I found out the reason is the signatures declared in the base class are ignored. Why are they ignored?

like image 657
Sandeep Avatar asked Sep 05 '10 22:09

Sandeep


2 Answers

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/

like image 163
Eric Lippert Avatar answered Nov 03 '22 15:11

Eric Lippert


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.

like image 20
mjfgates Avatar answered Nov 03 '22 17:11

mjfgates