Access Parent Class virtual method from inheriting Child Class Object - c#

I would like to know if it is possible to access the base virtual method using a inheriting class (which overrides the method) object.
I know this is not a good practice but the reason I want to know this is if it is technically possible. I don't follow such practice, asking just out of curiosity.
I did see a few similar questions but I did not get the answer I am looking for.
Example:
public class Parent
{
public virtual void Print()
{
Console.WriteLine("Print in Parent");
}
}
public class Child : Parent
{
public override void Print()
{
Console.WriteLine("Print in Child");
}
}
class Program
{
static void Main(string[] args)
{
Child c = new Child();
//or Parent child = new Child();
child.Print(); //Calls Child class method
((Parent)c).Print(); //Want Parent class method call
}
}

As per the linked duplicate I commented with, you can do it with some reflection tricks as such:
static void Main(string[] args)
{
Child child = new Child();
Action parentPrint = (Action)Activator.CreateInstance(typeof(Action), child, typeof(Parent).GetMethod("Print").MethodHandle.GetFunctionPointer());
parentPrint.Invoke();
}

Nope - it is not possible to invoke the Virtual method of Base class - The most derived implementation of the method is invoked in such scenarios. In the example given by you, it would print "Print in Child" in both the cases.

According to me, the best you can do is:
public class Parent
{
public virtual void Print()
{
Console.WriteLine("Print in Parent");
}
}
public class Child : Parent
{
public override void Print()
{
base.Print();
Console.WriteLine("Print in Child");
}
}
class Program
{
static void Main(string[] args)
{
Child c = new Child();
//or Parent child = new Child();
child.Print(); //Calls Child class method
((Parent)c).Print(); //Want Parent class method call
}
}

I wouldn't know when this would be helpful. But a decent workaround could be to either overload or write a dummy method that only calls the father class. It would look something like this:
public class Child : Parent
{
public void Print(bool onlyCallFather)
{
if(onlyCallFather)
base.Print();
else
Print();
}
}
And then in your main method:
class Program
{
static void Main(string[] args)
{
Child c = new Child();
child.Print(false); //Calls Child class method
child.Print(true); //Calls only the one at father
}
}
So it would do what you wanted to do. I've actually seen this type of workaround to tell if you want the base method to be called or not.

Related

How to execute a method in base class after child is fully initialized?

I implemented the following structure:
public abstract class A
{
protected A()
{
Test();
}
private void Test()
{
Console.WriteLine("2");
}
}
public class B : A
{
public B() : base()
{
Console.WriteLine("1");
}
}
When I create an instance of class B, the method Test() is executed before the constructor calls in class B. In my case, this method should run after the child is fully initialized. A possible way to make it work would be to make Test() accessible from B and call it at the end of its constructor. That would work but if someone creates another subclass of A , there is a chance that he forgets to call the method. My question is whether there is a more general solution in the base class to make sure that the method is executed after a child is fully initialized.
The answer is no.
There is nothing built into .NET or C# that can make sure methods are being called after all descendant constructors have executed.
A different approach would be some form of the factory pattern, where your class would basically just provide you with another instance that has been correctly set up, and all required methods called.
That can't be done cause constructor initializer doesn't work that way. Rather you can choose to pass some parameter to base constructor, parameters which may be specific to your child class like
public abstract class A
{
protected A(string data)
{
Test(data);
}
private void Test(string data)
{
Console.WriteLine(data);
}
}
public class B : A
{
public B() : base("1")
{
//some other initialization logic here
}
}
You can't directly "insert" a method call before calling constructor of base class, because it's calling a method on an uninitialized object. But you can use the template method pattern:
abstract class A {
protected A () {
BeforeTest ();
Test ();
}
protected abstract void BeforeTest ();
private void Test () {
Console.WriteLine ("2");
}
}
class B : A {
protected override void BeforeTest () {
Console.WriteLine ("1");
}
}
internal class Program {
public static void Main (string [] args) {
new B ();
}
}
Alternatively, you can make Test method virtual:
abstract class A {
protected A () {
Test ();
}
protected virtual void Test () {
Console.WriteLine ("2");
}
}
class B : A {
protected override void Test () {
Console.WriteLine ("1");
base.Test ();
}
}
internal class Program {
public static void Main (string [] args) {
new B ();
}
}
Both examples outputs the same result:
1
2

Calling an overwritten child method from parent class?

I am wondering what would theoretically be the output of this code?
Basically I am overwriting a method in the child class but I am calling that
method in the parent class. I am hoping the output of this would be "Child"
public class Animal {
protected virtual void Activate() {
Debug.Log("Parent");
}
void CallStuff() {
Activate();
}
}
public class Frog : Animal {
override void Activate() {
Debug.Log("Child");
}
}
If I were to have a frog instance frog and call ...
frog.CallStuff();
What would the output be?
Perhaps some examples will explain best:
Let's start with a base class:
public class Parent {
public virtual string WhatAmI() {
return "Parent";
}
public string Output() {
return this.WhatAmI();
}
}
Calling the Output method will, of course, give you "Parent"
new Parent().Output(); // "Parent"
Now let's override that virtual method
public class OverridingChild : Parent {
public override string WhatAmI() {
return "Child";
}
Now when you call Output(), it returns "Child"
new OverridingChild().Output(); // "Child"
And if you cast it to a Parent, you get the same result:
((Parent) new OverridingChild()).Output(); // "Child"
If you want the base class's value, you have to call base from within the inheriting class:
public class OverridingChild : Parent {
public override string WhatAmI() {
return "Child";
public string OutputBase() {
return base.WhatAmI();
}
}
new OverridingChild().OutputBase(); // "Parent"
Now for the confusing bit - here's how you can get either value, depending on what class the compiler thinks the object is:
public class NewMethodChild : Parent {
// note that "new" keyword
public new string WhatAmI() {
return "Child";
}
Calling the method directly when the compiler thinks it's the inheriting class gets you the expected result:
new NewMethodChild().WhatAmI(); // "Child"
But if you cast it to the base class, you get the Parent result:
((Parent) new NewMethodChild()).WhatAmI(); // "Parent"
And if you call the Output method, because it is defined at the Parent class it doesn't see the new WhatAmI method of the inheriting class, so it also outputs the base value:
new NewMethodChild().Output(); // "Parent"
Hope that clears things up.
the output would be "Child" It inherited the Call Stuff function but overrode the Activate function so you'd get Child

Accessing the correct function in an ArrayList of different child classes

Say I have the following three classes:
Parent class:
public class ParentClass {
public void foo() {
Debug.Log("Parent called!");
}
}
First child class:
public class ChildOne : ParentClass {
public new void foo() {
Debug.Log("Child one called!");
}
}
Second child class:
public class ChildTwo : ParentClass {
public new void foo() {
Debug.Log("Child two called!");
}
}
In a fourth class, I have an ArrayList that contains multiple ChildOne and ChildTwo objects. The ArrayList doesn't contain any objects of other types.
How do I access the foo() functions of the child objects?
public class Example {
public void someFunction() {
//...
ArrayList children = new ArrayList();
children.add(new ChildOne());
children.add(new ChildTwo());
children[0].foo(); //here I want to call the foo() function of the ChildOne object
children[1].foo(); //here I want to call the foo() function of the ChildTwo object
//...
}
}
Casting to ParentClass doesn't work, and I can't cast to one of the child classes because I don't know the type of each element.
If you can, you could use polymorphism instead of hiding the parent's foo function.
To achieve this result, we can transform the parent class to make the foo method virtual so we can override it in child class :
public class ParentClass {
public virtual void foo() {
Debug.Log("Parent called!");
}
}
Then in the children classes, we replace the new keyword by the override keyword :
public class ChildOne : ParentClass {
public override void foo() {
Debug.Log("Child one called!");
}
}
public class ChildTwo : ParentClass {
public override void foo() {
Debug.Log("Child two called!");
}
}
Using an ArrayList, you would call the foo method this way :
ArrayList children = new ArrayList();
children.Add(new ChildOne());
(children[0] as ParentClass).foo(); // will display "Child one called!"
Please note that children[0] returns an object. You have to cast this object to ParentClass to be able to call the foo method.
My last suggestion would be to use a List instead of the ArrayList. A List is strongly typed (you don't have to cast anything) and is a bit faster as there is no boxing/unboxing. There is not a lot of reason (if any) to use an ArrayList nowadays.
var children = new List<ParentClass>();
children.Add(new ChildOne());
children[0].foo(); // will display "Child one called!"
With reflection:
var child = children[0];
Type childType = child.GetType();
MethodInfo mi = childType.GetMethod("foo");
mi.Invoke(child, new object[]{});
As Kinetic states, best solution is to make ParentClass.foo() virtual. But, if you can't modify the parent class, then you'll need something else.
As an alternative to reflection, you can try something like this:
foreach (var child in children) {
if (child is ChildOne) {
((ChildOne)child).foo();
} else if (child is ChildTwo) {
((ChildTwo)child).foo();
} else {
// whatever you need to do to handle an unknown child
}
}
As Noob points out, this could be unwieldy with many child classes. Another alternative is to use an interface, like so:
public interface IFoo {
void foo();
}
public class ChildOne : ParentClass, IFoo {
public new void foo() {
Debug.Log("Child one called!");
}
}
public class ChildTwo : ParentClass, IFoo {
public new void foo() {
Debug.Log("Child two called!");
}
}
Then this:
foreach (var child in children) {
if (child is IFoo) {
((IFoo)child).foo();
} else {
// handle unknown child
}
}

Which constructor will called first in the below example

Which constructor will called first in the below example? When i put break point and execute it first pointed to child constructor but executed the parent class constructor, why this?
could any one please clarify me?
class Program
{
static void Main(string[] args)
{
Child child = new Child();
child.print();
Console.ReadLine();
}
}
public class Parent
{
public Parent()
{
Console.WriteLine("Parent Constructor.");
}
public void print()
{
Console.WriteLine("I'm a Parent Class.");
}
}
public class Child : Parent
{
public Child()
{
Console.WriteLine("Child Constructor.");
}
public new void print()
{
Console.WriteLine("I'm a Child Class.");
}
}
Constructors, when generated from C#, are invoked base-class first, so:
object()
then Parent()
then Child()
Essentially the chained base:.ctor({args}) is prepended to the local .ctor
For this reason you should avoid calling virtual methods during construction, as if Child overrides it, it could fail as Child hasn't initialized the fields defined there yet (they will be zeros).
In C++/CLI you get to choose what order to do things.
Parent is constructed first because it's at the heart of Child.
Child can't be constructed if it's core (Parent) isn't.
Note that the initialization of the class is not limited to executing its constructor. It also initializes its fields.
In the example below, you really want Child's constructor to show that x=3. If not, it would mean that your derived class can't be based on its ancestor behaviour.
public class Parent
{
public int x;
public Parent()
{
x = 3;
}
}
public class Child : Parent
{
public Child()
{
Console.WriteLine("Child Constructor. x="+x.ToString());
}
}

Override an overridden method (C#)

I'm trying to override an overridden method (if that makes sense!) in C#.
I have a scenario similar to the below, but when I have a breakpoint in the SampleMethod() in the "C" class it's not being hit, whilst the same breakpoint in the "B" method is being hit.
public class A
{
protected virtual void SampleMethod() {}
}
public class B : A
{
protected override void SampleMethod()
{
base.SampleMethod();
}
}
public class C : B
{
protected override void SampleMethod()
{
base.SampleMethod();
}
}
Thanks in advance!
Edit:
Ok, the context would help:
This is in the context of a composite control so class A inherits from CompositeControl and calls SampleMethod() after overriding the CreateChildControls() method.
Overriding can be performed in a chain as long as you like. The code you have shown is correct.
The only possible explanation for the behaviour you are seeing is that the object to which you are referring is actually of type B. I suggest that you double check this, and if things still don't make sense, post the other appropiate code.
Without seeing the code that calls SampleMethod, my guess would be that you have an object of type B and call SampleMethod on that.
The breakpoint is more than likely not being hit because you actually instantiated an instance of the "B" class.
Method override resolution works based on the actual runtime type of the class whose method should be called. So, if you had the following code:
C c = new C();
c.SampleMethod();
and the following:
C c = new C();
B b = (B)c;
b.SampleMethod();
both the runtime types of the class whose SampleMethod will be called is type B.
That solution works fine; although to actually use it outside the class the method is in, you need to set the access of SampleMethod to public rather than protected in all of the cases it appears, so:
public class A
{
public virtual void SampleMethod()
{
Console.WriteLine("lol");
}
}
public class B : A
{
public override void SampleMethod()
{
base.SampleMethod();
}
}
public class C : B
{
public override void SampleMethod()
{
base.SampleMethod();
}
}
for Overriding more than once in the hierarchy use something like this
// abstract class
abstract class A
{
public abstract void MethodOne();
}
// class B inherits A
class B : A
{
public override void MethodOne()
{
Console.WriteLine("From Class B");
}
}
// class C inherits B
class C : B
{
public override void MethodOne()
{
Console.WriteLine("From Class C");
}
}
// class D inherits C
class D : C
{
public override void MethodOne()
{
Console.WriteLine("From Class D");
}
}
// etc......
// class Main method Class
class MainClass
{
public static void Main()
{
B[] TestArray = new B[3];
B b1 = new B();
C c1 = new C();
D d1 = new D();
TestArray[0] = b1;
TestArray[1] = c1;
TestArray[2] = d1;
for (int i = 0; i < TestArray.Length; i++)
{
TestArray[i].MethodOne();
}
Console.ReadLine();
}
}
I did it in this code in this link
http://www.4shared.com/rar/0SG0Rklxce/OverridingMoeThanOnce.html
Method overriding is OOP feature that allows a child class to provide a specific implementation of a method that is already provided by one of its parent classes.

Categories

Resources