Is there any way to call the parent version of an overridden method? (C# .NET)
At the IL level, you could probably issue a call
rather than a callvirt
, and get the job done - but if we limit ourselves to C# ;-p (edit darn! the runtime stops you: VerificationException
: "Operation could destabilize the runtime."; remove the virtual
and it works fine; too clever by half...)
Inside the ChildClass
type, you can use base.methodTwo()
- however, this is not possible externally. Nor can you go down more than one level - there is no base.base.Foo()
support.
However, if you disable polymorphism using method-hiding, you can get the answer you want, but for bad reasons:
class ChildClass : ParentClass
{
new public int methodTwo() // bad, do not do
{
return 2;
}
}
Now you can get a different answer from the same object depending on whether the variable is defined as a ChildClass
or a ParentClass
.
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.
Calling the overridden method from the base class in C#
Which method is called is determined via polymorphism on the type that is passed into the AnotherObject constructor:
AnotherObject a = new AnotherObject(new A()); // invokes A.MyMethod()
AnotherObject b = new AnotherObject(new B()); // invokes B.MyMethod()
AnotherObject c = new AnotherObject(new BaseClass()); //invokes BaseClass.MyMethod()
Call parent method from child class c#
Found the solution.
In the parent I declare a new instance of the ChildClass() then bind the event handler in that class to the local method in the parent
In the child class I add a public event handler:
public EventHandler UpdateProgress;
In the parent I create a new instance of this child class then bind the local parent event to the public
eventhandler
in the child
ChildClass child = new ChildClass();
child.UpdateProgress += this.MyMethod;
child.LoadData(this.MyDataTable);
Then in the LoadData()
of the child class I can call
private LoadData() {
this.OnMyMethod();
}
Where OnMyMethod
is:
public void OnMyMethod()
{
// has the event handler been assigned?
if (this.UpdateProgress!= null)
{
// raise the event
this.UpdateProgress(this, new EventArgs());
}
}
This runs the event in the parent class
Calling the grand-parent implementation of an overridden method
This is a feature of C#. If you wish to expose this method to class C, consider refactoring A like so:
class A
{
private instance;
public virtual void Method1 ()
{
AMethod1();
}
protected void AMethod1()
{
instance = this;
do something;
}
}
This will enable you to call this method from within C:
class C : B
{
public override void Method1 ()
{
AMethod1();
// do something;
}
}
Does this keyword exist? When an overriding method needs to call the parent
You can't enforce it, but you can do it via a call like base.Foo(bar)
. base
allows you to access members of the class you're inheriting from.
You can kind of enforce this behavior 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 inheritence (e.g. class Dachsund : Dog
), you have to create yet another abstract method if you want Dog.Speak
to be guaranteed to execute.
How to call a method from a parent class's base class
One approach is to use explicit interface implementation in class A
:
This allows you to call A
's implementation - both from code within C
and from outside C
(by casting to IBob
first).
using System;
namespace ConsoleApp4
{
interface IBob
{
void foo();
}
class A : IBob
{
void IBob.foo()
{
Console.WriteLine("A");
}
public virtual void foo()
{
((IBob)this).foo();
}
}
class B : A
{
public override void foo()
{
Console.WriteLine("B");
}
}
class C : B
{
public override void foo()
{
Console.WriteLine("C");
// Writes B
base.foo();
// Writes A
((IBob)this).foo();
}
}
public class Program
{
static void Main(string[] args)
{
var sally = new C();
sally.foo(); // A B C
IBob sally2 = sally;
sally2.foo(); // A
Console.ReadLine();
}
}
}
Calling the inherit and the base method
To get your desired output you need to call the base GetName()
method in the GetName()
method of the Class B
. Like this for example:
public class A
{
public A(string N)
{
Name = N;
}
public string Name { get; set; }
public void GetName()
{
Console.Write(Name);
}
}
public class B : A
{
public B(string N) : base(N)
{
}
public new void GetName()
{
base.GetName();
Console.Write(new string(Name.Reverse().ToArray()));
}
}
This will out put foooof
Related Topics
C# 4.0: How to Use a Timespan as an Optional Parameter with a Default Value
How to Stop an Animation in C#/Wpf
Htmlagilitypack - Remove Script and Style
Check If an Executable Exists in the Windows Path
Regex Word Boundary Expressions
Entity Framework with Xml Files
Executenonquery Doesn't Return Results
C# String Replace with Dictionary
How to Print PDF on Default Network Printer Using Ghostscript (Gswin32C.Exe) Shell Command
Wpf Binding - Default Value for Empty String
How to Add Moving Effects to My Controls in C#
How to Copy Value from Class X to Class Y with the Same Property Name in C#
Visual Studio 2010: How to Enforce Build Order of Projects in a Solution
How to Convert Namevaluecollection to JSON String
How to Split an Ienumerable<String> into Groups of Ienumerable<String>