would `as` enable polymorphism? would pass a inherited class to a method which takes a base class enable polymorphism?

149 Views Asked by At

Fist of all, I will use virtual and override

for example, base class A has method A.do(), inherited class B has B.do() which overrides A's.

if I call (B as A).do(), which do() would it execute?

or, if there is a method void mymethod(A a) {a.do()}, now I call it by B b; mymethod(b), would it execute b.do()?

4

There are 4 best solutions below

0
abatishchev On BEST ANSWER

The most top override method always will be called, i.e. b.Do() or (b as A).Do() or ((A)b).Do() will call B.Do().

I don't know a way how to call a base method from child class if child class overrides it.

4
Nahum On
public class A
{
    public virtual void Do() { Console.Write("a"); }
    public void Do2() { Console.Write("a2"); }
}

public class B : A
{
    public override void Do() { Console.Write("b"); }
    public new void Do2() { Console.Write("b2"); }
}

class Program
{
    static void Main(string[] args)
    {
        B b = new B();
        A a = b;
        b.Do();               //b
        ( b as A ).Do();      //b
        a.Do();               //b
        ( (A)b ).Do();        //b

        ( b as A ).Do2();     //a2
        ( (A)b ).Do2();       //a2
        ( b ).Do2();          //b2
    }
}  

Output:

b b b b
a2 a2 b2
3
Hans Passant On

It entirely depends on whether the do() method was declared virtual or not. If it is not virtual then A.do() is called. If it is virtual then B.do() is called. It is the virtual keyword that enables polymorphism and allows calling a method independent of the type of the reference.

There is no mechanism in C# that allows directly calling a virtual A.do() method from a B object reference. The only exception is using base.do() inside an instance method of class B.

1
Caspar Kleijne On
public class A
{
    public A() { }
    public void Do() { Console.Write("A"); }

}

public class B : A
{
    public B() { }
    public void Do() { Console.Write("B");  }
}

class Program
{
    static void Main(string[] args)
    {
        B b = new B();
        b.Do(); //<-- outputs B
        (b as A).Do(); //<-- outputs A
      }
}

compiler warns for hiding not overriding:

Warning 1 'ConsoleApplication5.B.Do()' hides inherited member 'ConsoleApplication5.A.Do()'. Use the new keyword if hiding was intended. c:\Program.cs 18 21 ConsoleApplication5

that is since you are not overriding anything, but simply hiding the method from A.

however

public class A
{
    public A() { }
    public virtual void Do() { Console.Write("A"); }

}

public class B : A
{
    public B() { }
    public  override void Do() { Console.Write("B");  }
}

calls B twice, when method is overridden.