Can you force the method to be called inside the class constructor, otherwise you will throw a compilation error?

I have a class, Player, which inherits from AnimatedSprite. AnimatedSprite has a protected abstract loadAnimations method that Player must override to load the actual animations (since the animation will depend on the sprite image, it must be implemented by a class derived from AnimatedSprite).

However, although I force the class user to implement this method, is there a way to get the user to actually call this method, preferably inside the Player constructor, to ensure that the animation always loads? I'm sure C # does not have any language features for this (although I may be wrong), maybe there is a better class design sample that I can implement that I am observing?

As always, thanks in advance!

+4
source share
3 answers

Actually, it is not recommended to call virtual methods in the constructor, since they can use a state that has not yet been initialized (the corresponding constructor has not yet been called).

Personally, I would just use the abstract method that you call after the constructor, possibly through the factory:

static T Create<T>() where T : TheBase, new() { T obj = new T(); obj.Init(); return obj; } 
+10
source

I think calling methods inside the constructor is not a good approach ...

I am using this method:

  public abstract class AnimatedSprite { public void LoadAnimations() { OnLoadAnimations(); } protected abstract void OnLoadAnimations(); protected virtual void OnNextFrame() { }; .... } 
+4
source

I assume AnimatedSprite is an abstract class. Just add a call to the inisde AnimatedSprite method.

+1
source

All Articles