Access an overridden member of a base class using a derived class object (C #)

Given 2 types

class A { public virtual void Hello() { Console.WriteLine("A"); } } class B : A { public override void Hello() { Console.WriteLine("B"); } } 

and an instance of 'B' B b = new B();

Can I access the Hello() A thru b method? (I can think of exposing property A as in B, but not sure if there is another way)

I knew this was possible in C ++ , but it scratched my head in C #.

PS : Please, no talk around: "Why do you want this?" or "it's a bad design," etc.

+4
source share
3 answers

Not outside.

From within, an instance can call this via base.Hello() so you can add:

 public void Foo() { base.Hello(); } 
+9
source

In C #, this is not possible. Unfortunately.

+1
source

You can try shading:

 class A { public virtual void Hello() { Console.WriteLine("A"); } } class B : A { public new void Hello() { Console.WriteLine("B"); } } 

Then you can do:

  A b = new B(); b.Hello(); //prints A (B)b).Hello(); //prints B B b1 = new B(); b1.Hello(); //prints B 
+1
source

Source: https://habr.com/ru/post/1432357/


All Articles