Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

inheritance

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() method of A thru b ? (I can think of exposing A as property in B but not sure if there is another way)

I knew this is possible in c++ but was scratching my head in c#.

PS:Please no conversations around 'why do you want this?' or 'this is a bad design' etc.

like image 945
Antony Thomas Avatar asked Dec 20 '22 16:12

Antony Thomas


1 Answers

Not from the outside.

From the inside, the instance can call that, via base.Hello(), so you could add a:

public void Foo() { base.Hello(); }   
like image 107
Marc Gravell Avatar answered May 26 '23 11:05

Marc Gravell