Calling a Method from "base.base" class? - c#

"Assume the following code:
public class MultiplasHerancas
{
static GrandFather grandFather = new GrandFather();
static Father father = new Father();
static Child child = new Child();
public static void Test()
{
grandFather.WhoAreYou();
father.WhoAreYou();
child.WhoAreYou();
GrandFather anotherGrandFather = (GrandFather)child;
anotherGrandFather.WhoAreYou(); // Writes "I am a child"
}
}
public class GrandFather
{
public virtual void WhoAreYou()
{
Console.WriteLine("I am a GrandFather");
}
}
public class Father: GrandFather
{
public override void WhoAreYou()
{
Console.WriteLine("I am a Father");
}
}
public class Child : Father
{
public override void WhoAreYou()
{
Console.WriteLine("I am a Child");
}
}
I want to print "I Am a grandfather" from the "child" object.
How could i do the Child object execute a Method on a "base.base" class? I know i can do it executes the Base Method (it would Print " I Am a Father"), but i want to print "I Am a GrandFather"! if there is a way to do this, Is it recommended in OOP Design?
Note: I do not use / will use this method, I'm just wanting to intensify knowledge inheritance.

This can only be possible using Method Hiding -
public class GrandFather
{
public virtual void WhoAreYou()
{
Console.WriteLine("I am a GrandFather");
}
}
public class Father : GrandFather
{
public new void WhoAreYou()
{
Console.WriteLine("I am a Father");
}
}
public class Child : Father
{
public new void WhoAreYou()
{
Console.WriteLine("I am a Child");
}
}
And call it like this -
Child child = new Child();
((GrandFather)child).WhoAreYou();
Using new keyword hides the inherited member of base class in derived class.

Try to use the "new" keyword instead of "override" and remove the "virtual" keyword from methods;)

This program gives error when u run.
Make sure the object of child will refer parent class then use reference type casting calling method
Ex: child child = new grandfather();/here we are creating instance of child that refer parentclass./
((Grandfather)child).WhoAreYou();/* now we able to use reference type*/
Otherwise they show error under grandfather type casting .

Related

c# Instantiate object from subclass

Below I have some simple code with a Parent Class and a Child one that extends from it.
using System;
//Base Class
public class Parent {
public void foo() {
Console.WriteLine("Parent");
}
}
//Child Class
public class Child : Parent
{
new public void foo() {
Console.WriteLine("child");
}
}
Parent parent = new Child();
parent.foo();
I'm confused as to how the two lines above work. I would've expected the compiler to bark while trying to instantiate a Parent as its own subclass. Also, why then would 'parent.foo()' still call its Parent version.
At first you shouldn't hide base class method by using new keyword you should just override it by derived class method by using virtual and override keywords. It will also fix issue that method was called from base class not from derived.
For details how it works you should read about inheritance in C#.
When you hiding method by using new keyword it always using implementation of method that is in your declared type, in your case it Parent. But if you use virtual and override it using implementation of method that is in initialized type, in your case it Child.
using System;
public class Parent
{
public virtual void foo()
{
Console.WriteLine("Parent");
}
}
public class Child : Parent
{
public override void foo()
{
Console.WriteLine("Child");
}
}
why then would 'parent.foo()' still call its Parent version?
Because you are shadowing foo by using new.
Virtual or abstract methods can be overridden by subclasses:
//Base Class
public class Parent
{
public virtual void foo()
{
Console.WriteLine("Parent");
}
}
//Child Class
public class Child : Parent
{
public override void foo()
{
Console.WriteLine("child");
}
}
I would read all of the documentation linked in the comments to decide whch will work best for your use case.

How to Get Base Class Instance from a Derived Class

I don't know if this is possible, but I am trying to get the Base Class instance from a Derived Class. In C#, I can use the base keyword to access properties and methods of the Base Class (of course), but I want to use base itself. Attempting to do so results in a "Use of keyword 'base' is not valid in this context" error.
Example Code
public class SuperParent
{
public int SPID;
public SuperParent()
{
}
}
public class SubChild : SuperParent
{
public SubChild(int pSPID)
{
base.SPID = pSPID;
}
public int BaseSPID
{
get
{
SuperParent sp = base;
return sp.SPID;
}
}
}
If you're working with an instance of the derived class, there is no base instance.
An example:
class A
{
public void Foo() { ... }
}
class B : A
{
public void Bar() { ... }
}
What is not possible within B:
public void Bar()
{
// Use of keyword base not valid in this context
var baseOfThis = base;
}
You can do something like this:
public void Bar()
{
base.Foo();
}
And you can add another method like
public A GetBase()
{
return (A)this;
}
And then you can
public void Bar()
{
var baseOfThis = GetBase();
// equal to:
baseOfThis = (A)this;
}
So this GetBase() method is probably what you want.
The punchline is: If you have an instance of B, it inherits all properties and the non-overriden behaviour of A, but it does not consist of an instance of B which holds an (hidden but automatic) reference to an instance of A. You can cast your B instance to A, but it remains to be an instance of B.
Well you not provide code for your question, but i supsect you want something like
class Base
{
public virtual void Foo()
{
Console.WriteLine("base");
}
}
class Derived : Base
{
public override void Foo()
{
Console.WriteLine("derived");
}
//// bad
//public Base MyBase
//{
// get
// {
// return base; // Use of keyword 'base' is not valid in this context
// }
//}
// work but...
public Base MyBase
{
get
{
return (Base)this;
}
}
}
But keep in mind that MyBase is really of type Derived
new Derived().MyBase.Foo(); // output "derived"
the problem hasn't been explained as clearly as it could. however, typically, you may be better to use an abstract base class and methods and then override the required methods. you can then use the base.method as required in this case (otherwise you'll have just spun up an instance of the derived class).
public abstract class foo {
public virtual void bar(){..}
}
public class footwo : foo {
public override void bar(){
// do somethng else OR:
return base.bar();
}
}
}
The derived instance IS the base instance. It's just one object instance in memory.
example:
public class A : B
{
}
var thing = new A();
thing is an instance of an A, and is also an instance of a B.
You could for example, write this line:
B thing2 = thing;
Point 1: if you want to create the base class instance within child class than it does not worth. You already have public things accessible in child.
Point 2: If you have initialized child class and now want to get base class "instance" then how can you get that if it's not initialized(Because now the base class instance is not present in the physical memory, and there is just child class instance there)?
I interpreted what they were asking a bit differently than the other answers here so I figured I would offer my $0.02.
// Create a "Parent" class that has some attributes.
public class Parent
{
public string attribute_one { get; set; }
public string attribute_two { get; set; }
public string attribute_three { get; set; }
}
// Define a class called "Child" that inherits the
// attributes of the "Parent" class.
public class Child : Parent
{
public string attribute_four { get; set; }
public string attribute_five { get; set; }
public string attribute_six { get; set; }
}
// Create a new instance of the "Child" class with
// all attributes of the base and derived classes.
Child child = new Child {
attribute_one = "interesting";
attribute_two = "strings";
attribute_three = "to";
attribute_four = "put";
attribute_five = "all";
attribute_six = "together";
};
// Create an instance of the base class that we will
// populate with the derived class attributes.
Parent parent = new Parent();
// Using reflection we are able to get the attributes
// of the base class from the existing derived class.
foreach(PropertyInfo property in child.GetType().BaseType.GetProperties())
{
// Set the values in the base class using the ones
// that were set in the derived class above.
property.SetValue(parent, property.GetValue(child));
}
The result is a new object populated with the base class properties of the child class.
class Parent
{
private Parent _parent;
public Parent()
{
_parent = this;
}
protected Parent GetParent()
{
return _parent;
}
}
class Child : Parent
{
private Parent _parent;
public Child()
{
_parent = base.GetParent();
}
}

Are methods "virtual" by default or "not virtual"?:

According to this similar StackOverflow question and other articles, C# methods are "not virtual" by default, which I take it to mean that you cannot override them in a derived class.
If that is true, could you please explain to me how, in the example below, how I am able to implement the property LastName in the Child class which inherits from Base class without the property being marked as "virtual" inh the base class? Does the Child.LastName property "hide" (VB "Shadows") the same property in the base class? if so, why is the "new" key word not used in the Child.LastName pproperty to indicate this?
This test example seems to suggest to me that methods and virtual by default and, in the case of the LastName property, "overrrides" is implied, but I'm pretty sure that this is not the case.
What am I missing?
public class BaseClass
{
private string _FirstName;
public virtual string FirstName {
get { return _FirstName; }
set { _FirstName = value; }
}
private string _LastName;
public string LastName {
get { return _LastName; }
set { _LastName = value; }
}
public void Go()
{
MessageBox.Show("Going at default speed in Base Class");
}
public void Go(int speed)
{
MessageBox.Show("Going at " + speed.ToString() + " in Base Class");
}
}
public class Child : BaseClass
{
public override string FirstName {
get { return "Childs First Name"; }
set { base.FirstName = value; }
}
public string LastName {
get { return "Child's Last Name"; }
set { base.LastName = value; }
}
public void Go()
{
MessageBox.Show("Going in Child Class");
}
public void Go(int speed)
{
MessageBox.Show("Going at " + speed.ToString() + " in Child Class");
}
}
Methods are not virtual in C# by default. LastName in Child class hides the LastName from the BaseClass. As far as i can remember, this code can even compile, but warning will be provided by compiler, telling that new keyword should be used.
They're non-virtual by default.
The subclass hides the base's LastName property.
If you write:
BaseClass b = new Child(...);
Console.WriteLine(b.LastName);
You will see the base implementation is called.
The compiler will warn you about this when you compile the above code. It's standard practice to mark a member which hides a base's member as new.
public new string LastName {
get { return "Child's Last Name"; }
set { base.LastName = value; }
}
This is a very common C# programming interview question :)
A good understanding of Polymorphism will clear this up:
Polymorphism (C# Programming Guide)
Hiding Base Class Members with New Members
If you want your derived member to have the same name as a member in a base class, but you do not want it to participate in virtual invocation, you can use the new keyword. The new keyword is put before the return type of a class member that is being replaced. The following code provides an example:
public class BaseClass
{
public void DoWork() { WorkField++; }
public int WorkField;
public int WorkProperty
{
get { return 0; }
}
}
public class DerivedClass : BaseClass
{
public new void DoWork() { WorkField++; }
public new int WorkField;
public new int WorkProperty
{
get { return 0; }
}
}
Hidden base class members can still be accessed from client code by casting the instance of the derived class to an instance of the base class. For example:
DerivedClass B = new DerivedClass();
B.DoWork(); // Calls the new method.
BaseClass A = (BaseClass)B;
A.DoWork(); // Calls the old method.
Preventing Derived Classes from Overriding Virtual Members
Virtual members remain virtual indefinitely, regardless of how many classes have been declared between the virtual member and the class that originally declared it. If class A declares a virtual member, and class B derives from A, and class C derives from B, class C inherits the virtual member, and has the option to override it, regardless of whether class B declared an override for that member. The following code provides an example:
public class A
{
public virtual void DoWork() { }
}
public class B : A
{
public override void DoWork() { }
}
A derived class can stop virtual inheritance by declaring an override as sealed. This requires putting the sealed keyword before the override keyword in the class member declaration. The following code provides an example:
public class C : B
{
public sealed override void DoWork() { }
}
In the previous example, the method DoWork is no longer virtual to any class derived from C. It is still virtual for instances of C, even if they are cast to type B or type A. Sealed methods can be replaced by derived classes by using the new keyword, as the following example shows:
public class D : C
{
public new void DoWork() { }
}
In this case, if DoWork is called on D using a variable of type D, the new DoWork is called. If a variable of type C, B, or A is used to access an instance of D, a call to DoWork will follow the rules of virtual inheritance, routing those calls to the implementation of DoWork on class C.
well, you got it right. If it's not virtual, it gets hidden.
The new keyword brakes the virtual overriding in the inheritance hierarchy chain.
Simple example to read: Polymorphism, Method Hiding and Overriding in C#

How do I call the correct method from a child class in an array?

I'm not sure if this is allowed in C#, but I'm pretty sure I've done it in other languages before.
Let's say I have class, Parent, which has children Child0 and Child1. I make an array of type Parent where Array[0] is of type Child0 and Array[1] is of type Child1. In this scenario, how do I call the children's methods? When I type Array[0].Method(), it calls the Parent version of Method. How do I get it to call the Child0 version of Method? Is this possible?
You just have to declare Method as virtual in the base class:
public class Parent{
public virtual void Method(){
...
}
}
and override it in the heriting classes :
public class Child : Parent{
public override void Method(){
...
}
}
Note that if you don't really need a "standard" implementation in your Parent class, because all the inherithing classes have there own version, you can also set the method as abstract:
public class Parent{
abstract public void Method();
}
Then you don't have the choice and all the classes that inherit from Parent will have to provide an implementation for Method, otherwise you'll have a compile time error.
if you make the parent method virtual you can override the base method in your child classes.
public class Human
{
// Virtual method
public virtual void Say()
{
Console.WriteLine("i am a human");
}
}
public class Male: Human
{
// Override the virtual method
public override void Say()
{
Console.WriteLine("i am a male");
base.Draw(); // --> This will access the Say() method from the
//parent class.
}
}
add them to the array: (altho i would personally use a List<T>)
Human[] x = new Human[2];
x[0] = new Human();
x[1] = new Male();
print out results:
foreach (var i in x)
{
i.Say();
}
will print out
"i am a human" // --> (parent class implementation)
"i am a male" // --> (child class implementation)

C# How to execute code after object construction (postconstruction)

As you can see in the code below, the DoStuff() method is getting called before the Init() one during the construction of a Child object.
I'm in a situation where I have numerous child classes. Therefore, repeating a call to the DoStuff() method directly after Init() in the constructor of each child wouldn't be an elegant solution.
Is there any way I could create some kind of post constructor in the parent class that would be executed after the child's constructor? This way, I could call to the DoStuff() method there.
If you have any other design idea which could solve my problem, I'd like to hear it too!
abstract class Parent
{
public Parent()
{
DoStuff();
}
protected abstract void DoStuff();
}
class Child : Parent
{
public Child()
// DoStuff is called here before Init
// because of the preconstruction
{
Init();
}
private void Init()
{
// needs to be called before doing stuff
}
protected override void DoStuff()
{
// stuff
}
}
If you have a complex logic for constructing your objects then consider FactoryMethod pattern.
In your case I would implement it as a simple
public static Parent Construct(someParam)
method that takes some parameter and based on it decides which child class to instantiate.
You can remove your DoStuff() method call from the constructor and call it inside Construct() on the new instance.
Also, you should avoid virtual/abstract method calls in the constructors. See this question for more details: Virtual member call in a constructor
Let me introduce a general solution using some C# features. Note that this solution does not require you to use a factory pattern or invoke anything after constructing the object, and it works on any class with just implementing an interface with a single method.
First we declare an interface that our classes will have to implement:
public interface IInitialize {
void OnInitialize();
}
Next we add a static extension class for this interface, and add the Initialize method:
public static class InitializeExtensions
{
public static void Initialize<T>(this T obj) where T: IInitialize
{
if (obj.GetType() == typeof(T))
obj.OnInitialize();
}
}
Now, if we need a class and all of its descendants to call an initializer right after the object is fully constructed, all we need to do is implement IInitialize and append a line in the constructor:
public class Parent : IInitialize
{
public virtual void OnInitialize()
{
Console.WriteLine("Parent");
}
public Parent()
{
this.Initialize();
}
}
public class Child : Parent
{
public Child()
{
this.Initialize();
}
public override void OnInitialize()
{
Console.WriteLine("Child");
}
}
public class GrandChild : Child
{
public GrandChild()
{
this.Initialize();
}
public override void OnInitialize()
{
Console.WriteLine("GrandChild");
}
}
The trick is that when a derived class calls the extension method Initialize, that will suppress any calls not made from the actual class.
How about this:
abstract class Parent
{
public Parent()
{
Init();
DoStuff();
}
protected abstract void DoStuff();
protected abstract void Init();
}
class Child : Parent
{
public Child()
{
}
protected override void Init()
{
// needs to be called before doing stuff
}
protected override void DoStuff()
{
// stuff
}
}
As others have mentioned, you should use a Factory Pattern.
public class Parent
{
public Parent()
{
}
public virtual void PostConstructor()
{
}
}
public class Child : Parent
{
public override void PostConstructor()
{
base.PostConstructor();
// Your code here
}
}
public void FactoryMethod<T>() where T : Parent
{
T newobject = new T();
newobject.PostConstructor();
}
I would strongly suggest use Factory like a pattern.
If it's possible:
1. Push all your childs and abstract class into separate assembly.
2. Declare ctors of childs like internal methods, so no one out of that assembly is can construct them just by calling ctor.
3. Implement the Factory class to construct for caller specified objects type, which obviuoly will forse calling of abstract DoStuff() method after actual creation of anobject, but before returning it to caller.
Good thing about this is that: It will give you also additional level of abstraction, so if in the future you will need some more functions call or any other type of logical complexity, what you will need, is just add them into your Factory class.
That is.
Regards
In WPF applications, you can postpone the invokation of DoStuff() with the help of Dispatcher:
abstract class Parent
{
public Parent()
{
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(this.DoStuff));
}
private void DoStuff()
{
// stuff, could also be abstract or virtual
}
}
However, it is not guaranteed that DoStuff() will be called immediately after the constructor.
Correction: As per this answer, you can't determine when the base class's constructor is invoked during construction of the subclass.
E.g. This doesn't work:
public Child()
// DoStuff is called here after Init
// because of the overridden default constructor
{
Init();
base();
}
So, yes, as others have noted, if sequence of events matters, then the base class needs to be able to accommodate that by declaring abstract methods in order, or (better yet) by having the child class's implementation of DoStuff represent the sequence of events:
protected override void DoStuff()
{
Init();
base.DoStuff();
}
DoStuff is abstract. Just call Init from the top of DoStuff.
class MyBase
{
public MyBase()
{
//... do something
// finally call post constructor
PostConstructor<MyBase>();
}
public void PostConstructor<T>( )
{
// check
if (GetType() != typeof(T))
return;
// info
System.Diagnostics.Debug.WriteLine("Post constructor : " + GetType());
}
}
class MyChild : MyBase
{
public MyChild()
{
// ... do something
// ... call post constructor
PostConstructor<MyChild>();
}
}
How about...
public MyClass()
{
Dispatcher.UIThread.Post(RunAfterConstructor);
}
I also tried with Task.Run but that didn't work reliably.
Rather than using an abstract method, which would require you to implement the method in all descendant classes, you might try:
public class Parent
{
public Parent()
{
PostConstructor();
}
protected virtual void PostConstructor()
{
}
}
public class Child : Parent
{
protected override void PostConstructor()
{
base.PostConstructor();
/// do whatever initialization here that you require
}
}
public class ChildWithoutOverride
{
/// not necessary to override PostConstructor
}

Categories