Call the base method automatically

I need to call a base class method when you call overriden one (e.g. callor base). For instance:

class A { public void Fun() { Console.Write("Class A!"); } } class B : A { public void Fun() { Console.Write("Class B!"); } } 

I want to see on the screen

Class A! Class B!

when executing the following code:

 B b = new B(); b.Fun(); 

Can someone tell me, please, what needs to be changed in the code example or what is the best way to write in order to get the required result? Thanks.

+4
source share
4 answers

If you do not want to explicitly call it, and therefore call A.Fun() in a derived class, you can use something called a template template template :

 class A { public void Fun() { Console.Write("Class A!"); FunProtected(); } protected virtual void FunProtected() { } } class B : A { protected override void FunProtected() { Console.Write("Class B!"); } } 

This will give you:

 new A().Fun() -> "Class A!" new B().Fun() -> "Class A! Class B!" 
+19
source

If you need this behavior, you will need to change the platform / language..NET does not automatically call the base method. You must call this explicitly. Also, your method must be virtual or you will hide it in a derived class:

 class A { public virtual void Fun() { Console.Write("Class A!"); } } class B : A { public override void Fun() { // call the base method which will print Class A! base.Fun(); Console.Write("Class B!"); } } 

Now that you do this:

 B b = new B(); b.Fun(); 

You will get the desired result.

+8
source

Maybe so:

 interface IFun { void Fun(); } abstract class A : IFun { void IFun.Fun() { Console.Write("Class A!"); Fun(); } protected abstract void Fun(); } class B : A { protected override void Fun() { Console.Write("Class B!"); } } IFun b = new B(); b.Fun(); 

This works if the object reference is IFun.

+2
source

Just for reference, you can use a wrapper template that places A inside B. Here's a rough example!

 interface IFunClass { void Fun(); } class A : IFunClass { public void IFunClass.Fun() { Console.Write("Class A!"); } } class B : IFunClass { public B(IFunClass f) { this.m_SomethingFun = f; } public void IFunClass.Fun() { this.m_SomethingFun.Fun(); Console.Write("Class B!"); } private IFunClass m_SomethingFun; } A a = new A(); B b = new B(a); b.Fun() // will call a.Fun() first inside b.Fun() 
0
source

All Articles