Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call child method from parent c#

Tags:

c#

oop

My parent class is:

public Class Parent
{
    protected void foo()
    {
        bar();
    }

    protected void bar()
    {
        thing_a();
    }
}

My child class:

public class Child : Parent
{
    protected void bar()
    {
        thing_b();
    }
}

Is there any way that, when foo is called from the child class, Child's bar will be called, instead of Parent's?

Some context, though I doubt it matters: "foo" is Unity's FixedUpdate, "bar" is just some functionality that I need to change for children, but since I do other stuff on FixedUpdate, I don't want to copy the whole method only to change that one line.

like image 431
e2298 Avatar asked Apr 19 '18 16:04

e2298


2 Answers

Is there any way that, when foo is called from the child class, Child's bar will be called, instead of Parent's?

Yes, but that feature is off by default in C#, unlike Java.

In C# you turn it on like this:

public class Base
{
  protected void foo()
  {
    bar();
  }
  protected virtual void bar()
  {
    thing_a();
  }
}
public class Derived : Base
{
  protected override void bar()
  {
    thing_b();
  }
}

I note that you should have gotten a compiler warning explaining that this program looks wrong. Did you ignore the warning? Stop ignoring compiler warnings; they are there to inform you of your possible mistakes.

If you intend to have two methods of the same name but not override each other then first explain why that is, because that is a strange thing to want and almost certainly wrong. Second, you indicate that to the compiler with new:

public class Base
{
  protected void foo()
  {
    bar();
  }
  protected void bar()
  {
    thing_a();
  }
}
public class Derived : Base
{
  protected new void bar()
  {
    thing_b();
  }
}

Finally, a common pattern is to have the overriding method call the overridden method. You can do that like this:

public class Base
{
  protected void foo()
  {
    bar();
  }
  protected virtual void bar()
  {
    thing_a();
  }
}
public class Derived : Base
{
  protected override void bar()
  {
    thing_b();
    base.bar();
  }
}

Now a call to this.bar from foo will call thing_b() and then thing_a().

like image 134
Eric Lippert Avatar answered Sep 22 '22 23:09

Eric Lippert


First, you'll need to fix the access modifiers from private to public or protected. Then you will need to add the virtual keyword on the parent method and the override keyword on the child method.

public class Parent
{
    public void foo()
    {
        bar();
    }

    public virtual void bar()
    {
        thing_a();
    }
}

public class Child : Parent
{
    public override void bar()
    {
        thing_b();
    }
}
like image 40
Drew Sumido Avatar answered Sep 20 '22 23:09

Drew Sumido