How to Call Base.Base.Method()

C# how to call a method in the base of the base?

Generally, by overriding a class, you are accepting that it provides the interface and some of the behavior you want. A shouldn't know about it's super-superclass unless explicitly exposed in some way by its superclass. This is actually desirable, because you don't need to know how C is implemented when you subclass B. You shouldn't even know that C is involved.

If b's f() calls base.f(), a's base.f() just needs to call its own base.f() and you're done. If it doesn't, the only way to do that yourself is through intrusive methods based on Reflection. If you find yourself needing to do this, you've probably got an error in your design (violating the Law of Demeter, for one).

Force method to call base method from base class

Although it is not possible to achieve this directly, you could get the same effect by writing your own method that is not virtual, which calls the virtual after performing some fixed operation:

public class A
{
public void Say()
{
Console.Write("A");
SayImpl();
}
protected virtual void SayImpl()
{
// Do not write anything here:
// for the base class the writing is done in Say()
}
}

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

Now any class inheriting from A and implementing SayImpl() would have A prepended to its printout.

How to call base method from derived class instance in C#?

There is no way to access base method from outside the derived class.
You can either write a method in derived class that will call base method like this:

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

public void basePrint() { base.print(); }
}

Or you can user Reflection to get base method definition and invoke it but it's rather ugly.
Here is how to create DynamicMethod that calls base print method:

// Get MethodInfo of the base method
var methodInfo = typeof(A).GetMethod("Print", BindingFlags.Instance | BindingFlags.Public);

// Create DynamicMethod based on the methodInfo
var dynamicMethod = new DynamicMethod("BasePrint", methodInfo.ReturnType, new[] { methodInfo.DeclaringType }, methodInfo.DeclaringType);
// Create ILGenerator for the dynamic method
var il = dynamicMethod.GetILGenerator();

// Emit argument with index 0 - DeclaringType
il.Emit(OpCodes.Ldarg_0);
// Emit method call
il.EmitCall(OpCodes.Call, methodInfo, null);
// Emit method return value
il.Emit(OpCodes.Ret);

// Invoke method with target...
var b = new B();
dynamicMethod.Invoke(null, new object[] {b});

// ... or create a delegate and invoke method without target
var action = dynamicMethod.CreateDelegate(typeof(Action)) as Action;
action.Invoke();

Note that it'll work only for parameterless method. If you want to call method with parameters you'll have to put their types into the array with the DeclaringType and later emit all of them. Also you'll have to create delegate of type Action<parameterTypes or Func<returnType, parameterTypes> if the method returns something.

How to force inheriting class's method implementation to call base method before invoke own implantation?

I don't think that you can enforce the inheriting classes to always first call a method's super implementation, but:

Normally I use a Template method pattern for cases like this:

public abstract class TemplateEnforcer
{
private void TheSame()
{
Console.WriteLine("Everyone calls me;");
}

public void TemplateMethod()
{
this.TheSame();
this.NeedsImplementation();
}

protected abstract void NeedsImplementation();
}

public class TemplateImplementer : TemplateEnforcer
{
protected override void NeedsImplementation()
{
Console.WriteLine("Implemented in TemplateImplementer");
}
}

Code output for this call new TemplateImplementer().TemplateMethod():

    //Everyone calls me;
//Implemented in TemplateImplementer

Template method pattern benefits:

  1. Implementation of abstract method is forced.
  2. The code is kept DRY.
  3. Bugs are avoided and devs are guided in their development.

Call Body of derived method from the base method

Apparently you want to call the derived implementation of some logic from inside a context established in the base class (using(new UseSomething())).

This strongly implies that the base class has to be inherited from and does not make sense when it's not. This naturally leads to marking it abstract, which, in turn, naturally resolves your question:

public abstract class BaseClass
{
public void DoMe()
{
using (new UseSomething())
{
ActualDoMe();
}
}

protected abstract void ActualDoMe();
}

public class Der : BaseClass
{
protected override void ActualDoMe()
{
Console.WriteLine("der do me");
}
}

In a list - how can I call a method in the base only once

Add a static flag in the base, and adjust the flag

public class Base
{
public Base()
{
if (_instance == null)
_instance = this;//record the first instance
}
static Base _instance;
public virtual void foo()
{
if (_instance == this)
Debug.WriteLine("Base foo()");
}
}

How can I call the 'base implementation' of an overridden virtual method?

Using the C# language constructs, you cannot explicitly call the base function from outside the scope of A or B. If you really need to do that, then there is a flaw in your design - i.e. that function shouldn't be virtual to begin with, or part of the base function should be extracted to a separate non-virtual function.

You can from inside B.X however call A.X

class B : A
{
override void X() {
base.X();
Console.WriteLine("y");
}
}

But that's something else.

As Sasha Truf points out in this answer, you can do it through IL.
You can probably also accomplish it through reflection, as mhand points out in the comments.

Allways call base.Method in Override without mentioning it for simple Scripts

As far as I know, there is no way to automatically invoke the base class's virtual method when an overridden one is invoked. You must explicitly call it.

One of the things you can do is break the parent method up a bit more. Instead of having all of the code in a single overridable method like this:

public class Foo
{
public virtual void Update()
{
// Do stuff
}
}

public class Bar : Foo
{
public override void Update()
{
// Replaces the parents implementation of the
// Update method due to not calling base.Load();
}
}

Instead, you can use the Template Method Pattern to break it up in to multiple parts, so that the user can override the part that is meant explicitly for them.

public class Foo
{
public void Update()
{
this.OnUpdating();
this.PerformUpdate();
this.OnUpdated();
}

public virtual void PerformUpdate()
{
// Leave this empty. Let the subclass override it and
// do their own thing. Your parent code will still
// get called when Update() is called.
}

public void OnUpdating()
{
// Invoke code that you want to guarantee is always
// executed PRIOR the overridden PerformUpdate() method
// is finished.
}

public void OnUpdated()
{
// Invoke code that you want to guarantee is always
// executed AFTER the overridden PerformUpdate() method
// is finished.
}
}

public class Bar : Foo
{
public override void PerformUpdate()
{
// Do custom stuff, don't have to call base.PerformUpdate()
// because it already does it's code in OnUpdating()
// and OnUpdated().
}
}

Hope this makes sense. This is what I do in my game engine. I then document that a call to base.PerformUpdate() is not needed. Another option is to make the PerformUpdate() method abstract, forcing children to implement it. That makes it a bit more clearer that there is no need to invoke base.PerformUpdate().

public class Foo
{
public void Update()
{
this.OnUpdating();
this.PerformUpdate();
this.OnUpdated();
}

// Child class is required to implement this method.
// Only downside is you will no longer be able to instance
// the base class. If that is acceptable, then this is really
// the preferred way IMO for what you are wanting to do.
public abstract void PerformUpdate();

public void OnUpdating()
{
// Invoke code that you want to guarantee is always
// executed PRIOR the overridden PerformUpdate() method is finished.
}

public void OnUpdated()
{
// Invoke code that you want to guarantee is always
// executed AFTER the overridden PerformUpdate() method is finished.
}
}

In the end, this approach lets your base class handle its update code safely, by forcing children to implement their own update method that you do not depend on. Your base class can run through its update stuff before and after the child-class has run through its updates.

This basically lets you do this in your game code:

Bar myFoo = new Bar();
myFoo.Update();

And you can rest assured that your base class update methods get called, and the child update code will get called as well.

How to call the base F# method from a computation expression in an overridden method?

The problem here is that code inside async is compiled into a separate class, which then lives outside of the current class and so it cannot call the base methods in a typical way.

In this case, you can call the method before the async block. This works, because this is just a part of the normal method body. The method returns async which is not actually executed until you call it with do!

type T2 () =
inherit T1 ()
override __.Test () =
let baseTest = base.Test ()
async {
do! baseTest
}

This is a nice but limited trick. It will not work when you need to first compute some parameters and then pass them to Test (because you cannot make baseTest a function - it has to be a value). The only option in that case is to define a helper method that calls the base method:

type T2 () =
inherit T1 ()
member private x.BaseTest() =
base.Test ()
override x.Test () =
async {
do! x.BaseTest()
}

I think this is a bit nicer than your workaround, because it does not require any virtual methods in the base class. base.Test call will work from a private method of the derived class.



Related Topics



Leave a reply



Submit