Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you force a method to be called inside a class constructor, else throw compile error?

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

However, while I force the class user to implement the method, is there a way to force the user to actually call this method, preferably inside the Player constructor, to ensure that the animations are always loaded? I'm pretty sure C# doesn't have any language features to do this (though I could be wrong), so perhaps there's a better class design pattern that I can implement which I'm overseeing?

As always, thanks in advance!

like image 711
Cooper Avatar asked Dec 07 '22 19:12

Cooper


2 Answers

It is actually not recommended to call virtual methods in a constructor, since they may use state that is not yet initialized (the relevant constructor has not yet been called).

Personally I would just had an abstract method that you call after the constructor, maybe via a factory:

static T Create<T>() where T : TheBase, new()
{
    T obj = new T();
    obj.Init();
    return obj;
}
like image 104
Marc Gravell Avatar answered Dec 30 '22 11:12

Marc Gravell


i think that calling methods inside constructor is not a good approach...

i'm used to do this way:

 public abstract class AnimatedSprite
 {
      public void LoadAnimations() 
      {
           OnLoadAnimations();
      }

      protected abstract void OnLoadAnimations();
      protected virtual void OnNextFrame() { };
      ....          
 }
like image 36
Blau Avatar answered Dec 30 '22 12:12

Blau