Call subclass `new` method from parent [duplicate] - c#

This question already has answers here:
Why does calling a method in my derived class call the base class method?
(16 answers)
Closed 3 years ago.
I have a base and sub class such as:
class BaseClass
{
public void MethodA()
{
MethodB();
}
public void MethodB()
{
Debug.Log("BaseClass MethodB");
}
}
class SubClass : BaseClass
{
public new void MethodB() // <- without `new` keyword there's a warning on this line
{
Debug.Log("SubClass MethodB");
base.MethodB();
}
}
When the MethodA of the BaseClass instance is called it calls MethodB but only of the BaseClass, and not of the SubClass first. e.g.
var subclass = new SubClass();
subclass.MethodA(); // Does not log "SubClass MethodB" first. Only logs "BaseClass MethodB"
How do you make sure the parent methods call the subclass methods?
Note, without the new keyword on the MethodB line, Visual Studio gives a warning: 'SubClass.MethodB()' hides inherited member 'BaseClass.MethodB()'. Use the new keyword if hiding was intended.

To get Subclass.MethodB to be called from your base class you need to use the virtual and override keywords. For example:
class BaseClass
{
public void MethodA() // invoking this will correctly log "SubClass MethodB" followed by "BaseClass MethodB"
{
MethodB();
}
public virtual void MethodB()
{
Debug.Log("BaseClass MethodB");
}
}
class SubClass : BaseClass
{
public override void MethodB()
{
Debug.Log("SubClass MethodB");
base.MethodB();
}
}

Related

Insert code from child class method in middle of base class method [duplicate]

I have a base class and a class inheriting base. The base class has several virtual functions that the inherited class may override. However, the virtual functions in the base class has code that MUST to run before the inherited class overrides get called. Is there some way that I can call the base classes virtual functions first then the inherited class overrides. Without making a call to base.function().
I know I can simply make two functions, one that gets called, the other virtual. But is there a way I can keep the same names as well? I know I may need to change some things around.
class myBase
{
public virtual myFunction()
{ /* must-run code, Called first */ }
}
class myInherited : myBase
{
public override myFunction()
{ /* don't use base.myFunction();,
called from base.myFunction(); */ }
}
Similar question here.
C# doesn't have support for automatically enforcing this, but
you can enforce it by using the template method pattern. For example, imagine you had this code:
abstract class Animal
{
public virtual void Speak()
{
Console.WriteLine("I'm an animal.");
}
}
class Dog : Animal
{
public override void Speak()
{
base.Speak();
Console.WriteLine("I'm a dog.");
}
}
The trouble here is that any class inheriting from Animal needs to call base.Speak(); to ensure the base behavior is executed. You can automatically enforce this by taking the following (slightly different) approach:
abstract class Animal
{
public void Speak()
{
Console.WriteLine("I'm an animal.");
DoSpeak();
}
protected abstract void DoSpeak();
}
class Dog : Animal
{
protected override void DoSpeak()
{
Console.WriteLine("I'm a dog.");
}
}
In this case, clients still only see the polymorphic Speak method, but the Animal.Speak behavior is guaranteed to execute. The problem is that if you have further inheritance (e.g. class Dachshund : Dog), you have to create yet another abstract method if you want Dog.Speak to be guaranteed to execute.
A common solution that can be found in the .NET Framework is to split a method in a public method XXX and a protected, virtual method OnXXX that is called by the public method. For your example, it would look like this:
class MyBase
{
public void MyMethod()
{
// do something
OnMyMethod();
// do something
}
protected virtual void OnMyMethod()
{
}
}
and
class MyInherited : MyBase
{
protected override void OnMyMethod()
{
// do something
}
}
public abstract class BaseTemp
{
public void printBase() {
Console.WriteLine("base");
print();
}
public abstract void print();
}
public class TempA: BaseTemp
{
public override void print()
{
Console.WriteLine("TempA");
}
}
public class TempB: BaseTemp
{
public override void print()
{
Console.WriteLine("TempB");
}
}
There is no way to do what you're seeking other than the 2 ways you already named.
Either you make 2 functions in the base class, one that gets called and the other virtual.
Or you call base.functionName in the sub-class.
Not exactly. But I've done something similar using abstract methods.
Abstract methods must be overriden by derived classes. Abstract procs are virtual so you can be sure that when the base class calls them the derived class's version is called. Then have your base class's "Must Run Code" call the abstract proc after running. voila, your base class's code always runs first (make sure the base class proc is no longer virtual) followed by your derived class's code.
class myBase
{
public /* virtual */ myFunction() // remove virtual as we always want base class's function called here
{ /* must-run code, Called first */
// call derived object's code
myDerivedMustcallFunction();
}
public abstract myDerivedMustCallFunction() { /* abstract functions are blank */ }
}
class myInherited : myBase
{
public override myDerivedMustCallFunction()
{ /* code to be run in derived class here */ }
}
What do you think of this?
class myBase
{
public void myFunctionWrapper()
{
// do stuff that must happen first
// then call overridden function
this.myFunction();
}
public virtual void myFunction(){
// default implementation that can be overriden
}
}
class myInherited : myBase
{
public override void myFunction()
{
}
}

overriding methods in C# and avoid duplicate code [duplicate]

This question already has answers here:
Force base method call
(14 answers)
Closed 4 years ago.
I would like to override a method, but i still want the parent method to be called when i override. When i try to use :base() to call parent method, it says unexpected token.
public class A
{
public virtual void DoStuff()
{
//some code
}
}
public class B : A
{
public override void DoStuff() : base()
{
//some other code
}
}
In java i would be :
super.DoStuff()
You have the wrong syntax, you can call the base method using the base keyword anywhere in the body of the method. The :base() syntax is only for constructors.
public class A
{
public virtual void DoStuff()
{
//some code
}
}
public class B : A
{
public override void DoStuff()
{
base.DoStuff();
}
}

Calling derived class method instead base class method c# [duplicate]

This question already has answers here:
How do I call a derived class method from the base class?
(2 answers)
Closed 4 years ago.
I have this array in program
ClassA[] array=new ClassA[20];
array[0]=new ClassB();
array[1]=new ClassA();
This is the class file
public class ClassA
{
public void method()
{
Console.WriteLine("1");
}
}
public class ClassB : ClassA
{
public void method()
{
Console.WriteLine("2");
}
}
It writes 1, in both cases, but i want in first case to write 2, (to call method of ClassB).
How to do that?
You have to use override keyword in C# when you want to override method in child class.
public class ClassA
{
public virtual void method()
{
Console.WriteLine("1");
}
}
public class ClassB : ClassA
{
public override void method()
{
Console.WriteLine("2");
}
}
Regards.

Is the keyword "virtual" optional or mandatory in a overridable method? [duplicate]

This question already has answers here:
Overriding vs method hiding [duplicate]
(3 answers)
Closed 5 years ago.
In C #, why we don't have a compilation error even if we forget the keyword "Virtual" in a method of a base class, redefined in a derived class.
I learnded that this keyword is mandatory to override a method
is not it ?
public class Mother
{
public void Speak()
{
Console.WriteLine("Mother !");
}
}
public class Son : Mother
{
public void Speak()
{
Console.WriteLine("Son!!");
}
}
Should be :
public class Mother
{
public virtual void Speak()
{
Console.WriteLine("Mother !");
}
}
public class Son : Mother
{
public override void Speak()
{
Console.WriteLine("Son!!");
}
}
Basically, Virtual and Override works on dynamic binding. The dynamic binding will be decided at run-time Compiler doesn't know that which virtual method will override in the derived class. That why it doesn't give you an error. This will be decided at run-time. Which derived class will be using at run-time.

Should you call base.methodName or this.methodName [duplicate]

This question already has answers here:
Difference between this and base
(9 answers)
Closed 9 years ago.
If you are writing code in a class that inherits from a base class and you want to call a protected or public method on that base class, is it best (right or wrong or otherwise) to call base.MyProtectedMethod() or this.MyProtectedMethod() (in c#)? What would the difference be? Both seem to work.
For example:
public class MyBase()
{
....
protected void DoStuff()
{
// some stuff
}
}
public class MyChildClass() : MyBase
{
public MyNewMethod()
{
// do some work
this.DoStuff();
base.DoStuff();
}
}
Does this just to the same thing twice in MyNewMethod?
This does exactly the same thing in MyNewMethod.
I would only recommend using base. when it is actually required, ie: when you need to explicitly calling the base class version of a method from within an overridden method.
Do you want to explicitly call up the parent class? Then use base.
If you don't want to, use this.
This shows a great example on using base.
Just to illustrate Reed and Kevin's answers:
namespace ConsoleApplication1
{
class A
{
public virtual void Speak()
{
Hello();
}
virtual protected void Hello()
{
Console.WriteLine("Hello from A");
}
}
class B : A
{
public override void Speak()
{
base.Hello(); //Hello from A
this.Hello(); //Hello from B
}
override protected void Hello()
{
Console.WriteLine("Hello from B");
}
}
class Program
{
static void Main(string[] args)
{
B b = new B();
b.Speak();
}
}
}

Categories