views:

264

answers:

8

Here one more basic question asked in MS interview recently

class A {
    public virtual void Method1(){}

    public void Method2() {
        Method1();
    }
}

class B:A {
    public override void Method1() { }
}

class main {
    A obk = new B();
    obk.Method2(); 
}

So which function gets called? Sorry for the typos.

+13  A: 
B.Method1();

gets called because it properly overrides the virtual method A.Method1();

Justin Niessner
+4  A: 

In this case B.Method1 gets called. This is because even though the variable is typed as A the actual type of the instance is B. The CLR polymorphically dispatches calls to Method1 based on the actual type of the instance, not the type of the variable.

Andrew Hare
+2  A: 

B.Method1() is called due to the override.

Seb
+1  A: 

The rule is "overriding member in the most derived class", which in this case would be "B".

kekekela
+4  A: 

Method1 from class B will be called, as you can see by running the below program:

class Program
{
    static void Main(string[] args)
    {
        var b = new B();
        b.Method2();

        Console.ReadLine();
    }
}

class A 
{ 

    public virtual void Method1()
    {
         Console.WriteLine("Method1 in class A");
    } 

    public void Method2() 
    { 
         Method1(); 
    } 
}

class B : A 
{ 
    public override void Method1() 
    { 
         Console.WriteLine("Method1 in class B"); 
    } 
} 
klausbyskov
+2  A: 

B.Method1 is called because it is overridden in the class definition.

Ardman
+1  A: 

The question is a little ambigious...but...

obk.method2() is called. In turn, it calls obk.Method1, which, since it is an instance of B, has been overridden by B.Method1. So B.Method1 is what eventually gets called.

mgroves
A: 

As everybody else has said, B.Method2 gets called. Here is a few other pieces of information so you understand what's going on:

((A)B).Method2();
B.Method2();

These will both call B.Method1() because it was properly overridden. In order to call A's Method1, there must be a base.Method1() call made from B (which is often but not always done in B.Method1's implementation).

If, however, B was defined in this way:

class B:A {
new public void Method1() { }

... then A's Method1() would be called because Method1 was not actually overridden, it was hidden and tucked away outside the rules of polymorphism. In general, this is typically a bad thing to do. Not always, but make sure you know very well what you're doing and why you're doing it if you ever do something like this.

On the flip side, using new in this way makes for some interesting interview questions as well.

Jaxidian