How to call top class constructor? - c#

I hope I can explain this problem right, it's a bit confusing for me.
I have been working on a game library similar to flixel but, using C#'s XNA framework instead of Flash. Right now the current class layout is something like this.
ClxBasic -> ClxObject -> ClxSprite
Each class has a constructor and calls the constructor for the class below it. I use this code to do this.
namespace Test
{
public class ClxBasic
{
public ClxBasic()
{
Constructor();
}
public void Constructor()
{
DoSomething();
}
}
public class ClxObject : ClxBasic
{
public ClxObject() : base()
{
Constructor();
}
public void Constructor()
{
DoSomething();
}
}
public class ClxSprite : ClxObject
{
public ClxSprite() : base()
{
Constructor();
}
public void Constructor()
{
DoSomething();
}
}
}
So basically when I create a new ClxSprite it calls the ClxSprite constructor, then all the ones below it (ClxObject and ClxBasic).
I'm sure there is an easier way to do this and I am all ears.
However, my bigger issue is actually how to properly derive and override methods from the other classes.
The issue is that when creating a class that extends from ClxSprite, for example, when calling a method that was overridden from the most basic class (ClxBasic), it will only call the bottom method and not the top.
The reason I need to do this is because I have a global class which keeps control of all the objects derived from ClxBasic by adding themselves to a list in the ClxBasic constructor.
Here's some example code.
namespace Test
{
public static class ClxG()
{
public static List<ClxBasic> GlobalObjects; //All objects will be added here by the ClxBasic constructor
ClxSprite test = new ClxSprite();
GlobalObjects.Add(test);
public static Update()
{
foreach(ClxBasic basic in GlobalObjects)
basic.Update(); //Calling this calls ClxBasic.Update() when it should call ClxSprite.Update()
}
}
}
When calling basic.Update() it goes to the bottom Update, the one located in ClxBasic, despite the object being a ClxObject or ClxSprite or other derived class.
I have a limited fix as well, by changing the ClxBasic to ClxSprite in the foreach loop, you can call that classes constructor method properly. However, when making custom classes based off of the library who override a method, the lower Update is called.
However, the limit is that you can't add classes I didn't specifically plan for. For example, if I were to derive a class Player from ClxSprite and, override the Update() method, it would get added to the GlobalObjects list but, never have it's update called, the highest it will go is ClxSprite's.
The way I want it to work is, in Game1.cs I want to just be able to put FlxG.Update() in the Game.Update() loop and just be able to create the object and have my framework handle the rest.
I hope I've made a bit of sense, the whole thing feels like some sort of inheritance inception and kind of makes my brain hurt.

To also call a base class method as part of a child class implementation, you'd do this:
class Base {
public virtual void Method() {
// ...
}
}
class Derived : Base {
public override void Method() {
base.Method();
// ....
}
}
class Derived2 : Derived {
public override void Method() {
base.Method();
// ....
}
}
But the child method is not required to call the base one.
Constructors, on the other hand, are always required to (ultimately) call a base constructor.
Now, if you want a base class method to always be called as part of some processing, you can employ the template method pattern. Basically your base class has a non-virtual method that drives an algorithm that calls virtual (or abstract) methods; which the child classes can override to create their own versions.

You are properly using base() to call the constructors of your base classes. As for how you are defining your constructors, why is Constructor() a separate method, rather than the body of the different constructors? If you are only planning on calling Constructor() when you create a new insance of one of your classes, I would recommend moving Constructor() back into your actual constructors, like so:
namespace Test
{
public class ClxBasic
{
public ClxBasic()
{
// Do Something
}
}
public class ClxObject : ClxBasic
{
public ClxObject() : base()
{
// Do Something
}
}
public class ClxSprite : ClxObject
{
public ClxSprite() : base()
{
// Do Something
}
}
}
As for being able to call the appropriate Update() function, depending on the actual class of your object, you would accomplish this using the virtual and override keywords. You would use them like so:
namespace Test
{
public class ClxBasic
{
// Define the base function that can be overridden
// in subclasses.
public virtual void Update()
{
// Do Some Updates
}
}
public class ClxObject : ClxBasic
{
// We're overridiung the base function, so we
// must mark this function as an override.
public override void Update()
{
// Do Some Updates
}
}
public class ClxSprite : ClxObject
{
// We're overridiung the base function, so we
// must mark this function as an override.
public override void Update()
{
// Do Some Updates
}
}
}
When you call Update() on an object that is an instance of a class derived from ClxBasic, the top-level Update() function in that objects inheritance-chain will be called. For instance:
ClxBasic clxBasic = new ClxBasic(); // Calls ClxBasic.Update()
ClxBasic clxObject = new ClxObject(); // Calls ClxObject.Update()
ClxBasic clxSprite = new ClxSprite(); // Calls ClxSprite.Update()
In addition, if you want your Update() functions to call the Update() function of their parent, you can use the base keyword.
For example:
public class ClxSprite : ClxObject
{
// We're overridiung the base function, so we
// must mark this function as an override.
public override void Update()
{
base.Update(); // Will call ClxObject's Update() function
// Do Some Updates
}
}

Based on your description, your goal seems to be to achieve polymorphic behavior among different game classes. A better solution is to define an interface that different game classes must implement. Then you can put all of your game objects in one generic container, such as an array list, and then have the master game loop iterate through the object list and invoke each object's update method the method during each overall update. I would design the classes like this:
interface IUpdatable {
void doUpdate();
}
class GameClassA : IUpdatable {
void doUpdate() { // }
}
class GameClassB : IUpdatable {
void doUpdate() { // }
}
etc.
Your goal is to achieve polymorphic behavior among objects of different classes but not necessarily to share data and common functionality. While you can achieve polymorphism through inheritance as well, it is better achieved in this case through simple interfaces and composition.

Related

methoddecorator.fody is it possible to invoke a instance method with method OnExit

I'm working on a AOP project ,which there is a class (call it classA) inherited from an other class (call is ParentClass) . Code like bellow
[Interceptor]
class ParentClass
{
protected void Init()
{
...
}
}
class classA : ParentClass
{
}
When creating a new instance of classA , i want a call of ParentClass's Init() by AOP , but i find it's hard for me .
Please Help.
update.
Hi,guys. There is one thing you should know, i want an AOP interception , not a method call from child class. because i have too many objects and i want a immediately call within onExit of a .ctor .
public class MyParentClass
{
public virtual void SomeMethod()
{
/* do parent class stuff here */
}
}
public class MyChildClass : MyParentClass
{
public override void SomeMethod()
{
/* do child class stuff here */
base.SomeMethod(); // <--- This will call the parent class method
}
}
Using Parent class any method describe then used virtual
Using child class any method describe then used override

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()
{
}
}

Pass-through constructors from its base class

An external framework has the following classes:
public class Boatmaker
{
}
public class Wood
{
}
public class Axe
{
}
public class Lake
{
}
public class Boat
{
public Boat(Wood wood, Axe axe) {
}
public Boat (Boatmaker maker) {
}
public Boat (Lake lake) {}
}
I need to do a lot of subclassing of Boat. For each of my subclasses, I have to assume that the external framework may want to instantiate it via any of the above constructors. So my subclasses get pass-through constructors. Notice how they never go away:
public class SmallBoat: Boat
{
public void DoSmallBoatStuff() {
// some code here
}
private void Initialize() {
this.DoSmallBoatStuff();
}
public SmallBoat(Wood wood, Axe axe): base(wood, axe) {
this.Initialize();
}
public SmallBoat (Boatmaker maker): base(maker) {
this.Initialize();
}
public SmallBoat (Lake lake): base(lake) {
this.Initialize();
}
}
public class Canoe: SmallBoat
{
public void DoCanoeStuff() {
// some code here
}
private void Initialize() {
this.DoCanoeStuff();
}
public Canoe(Wood wood, Axe axe): base(wood, axe) {
this.Initialize();
}
public Canoe (Boatmaker maker): base(maker) {
this.Initialize();
}
public Canoe(Lake lake): base(lake) {
this.Initialize();
}
}
I am wondering if there is a way to simplify the appearance of the code. The only difference between the way the constructors are written in SmallBoat and Canoe is the word SmallBoat or Canoe. Everything else is the same.
So if there were a way to write a constructor without actually using the name of the class in the constructor, it would help a lot. I could use direct copy and paste without a .tt file (which is not really viable for me -- most of my work is not done in Visual Studio). Is there a way to do that?
No. There is not. You have to specify which constructors of the base class you want to make available from the current class. There is no way to write the constructor without mentioning the real class name.
It might be a simplification you are showing, but if Initialize is the only method called, you might want to move that call to the base class calling a protected Initialize method you can override from the implementing classes. (You have to take in consideration the order of calling that method and instantiating properties/fields. You can run into trouble there, so it might not be viable in your situation)
1. Automation of code typing
There is code snippet : ctor that helps create "only" default constructor.
To use it type ctor an tabulation twice.
The original code snippet can be copied to create your own.
In Visual Studio, go in Tools menu/Code snippet manager.
You can see here the directories of the snippet files.
You can copy a snippet ( ctor.snippet for instance ) to "My Code Snippets", rename it and edit.
2. Design of the boat hierarchy
The boat hierarchy can also be designed so there is only a default constructor in the base class, and you have public properties or public method(s) in the base class to provide Lake, Axe, BoatMaker, ...
If you can change the design, I highly recommend separate object instantiation from the object itself. This way, the Factory Method combining with Template Method design pattern comes very helpful:
public abstract class BoatFactory
{ protected abstract void Initialize();
protected Wood Wood;
protected Axe Axe
protected Boatmaker Boatmaker ;
public Boat MakeBoat(Wood wood, Axe axe)
{
this.Wood = wood;
this.Axe = axe;
Initialize();
}
public Boat MakeBoat(Boatmaker maker)
{
this.Boatmaker = Boatmaker ;
Initialize();
}
public Boat MakeBoat(Lake lake)
{
this.Lake = lake;
Initialize();
}
}
public class SmallBoatFactory : BoatFactory
{
protected override void Initialize()
{
// do customized init operations here
}
}

C#: Override inherited method, but not for the whole class

I'm just playing around a bit with inheritance and/or polymorphism in C#, and since my OOP skills are very, very basic I'm wondering if this is possible:
I have a class which inherits a method from a base class:
class BaseClass {
public void Init () {
// Do basic stuff.
}
}
class LoginTest : BaseClass {
public void StraightMethod () {
// Do stuff based on the actions in the inherited Init() method from BaseClass.
}
public void ExceptionMethod () {
// Do stuff where I don't want to do the actions in the inherited method.
// That is, skip or override the Init() method in the BaseClass class.
}
}
I know I can override the Init() method for the whole class, but is it possible to override it, or the code in it, for just the ExceptionMethod() method? These methods are run exclusively, so that for example one initialization of the LoginTest class will only run LoginClass.ExceptionMethod(), while another one might run LoginClass.StraightMethod().
And yes, I know that good design will eliminate the need for things like this. But first of all, I'm not doing software engineering here, so being pragmatic is often OK without ruining some design or other principles. Second, this is more a question of whether or not something can be done, rather than the wiseness of it.
Note that these classes and methods are UnitTest methods, so the Init() method is a [TestInitialize] method. Hence, it's called automatically when LoginTest inherits from the BaseClass.
No, you can't selectively override the Init method, but by making the Init method virtual, you can specify which version of the method you want to call with the base and this keywords:
class BaseClass
{
// This method must become virtual
public virtual void Init()
{
// Do basic stuff.
}
}
class LoginTest : BaseClass
{
public override void Init()
{
// Other stuff
}
public void StraightMethod()
{
// Do stuff based on the actions in the inherited Init() method from BaseClass.
base.Init();
}
public void ExceptionMethod()
{
// Do stuff where I don't want to do the actions in the inherited method.
// That is, skip or override the Init() method in the BaseClass class.
this.Init();
}
}
The method isn't virtual, so it's not possible to override it at all, ever.
You can't conditionally override the method, but you can call each one individually (if you provide the base functionality in the base class).
class BaseClass {
public virtual void Init () {
// Do basic stuff.
}
}
class LoginTest : Baseclass {
public override void Init() {
//do overridden stuff
}
public void StraightMehthod () {
this.Init(); // Call the overridden
}
public void ExceptionMethod () {
base.Init(); // Call the base specifically
}
}
As you have said though, this is probably not something you want to do as someone using this code will be very confused by the behavior.
You also have the option to do this.
class BaseClass
{
public void Init()
{
// Do basic stuff.
Console.WriteLine("BaseClass.Init");
}
}
class LoginTest : BaseClass
{
public void StraightMehthod()
{
// Do stuff based on the actions in the inherited Init() method from BaseClass.
base.Init();
}
public void ExceptionMethod()
{
// Do stuff where I don't want to do the actions in the inherited method.
this.Init();
// That is, skip or override the Init() method in the BaseClass class.
}
private new void Init()
{
Console.WriteLine("LoginTest.Init");
}
}

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