Search code examples
c#.netlambdavirtual

Action<T> vs virtual methods


Consider I have a game-creation framework, with a basic class called Game.

// Action version
public class Game 
{
    public Action<float> OnUpdate;
    public void Update(float mFrameTime) { OnUpdate.Invoke(mFrameTime); }
}

// Virtual version
public class Game 
{
    public virtual void Update(float mFrameTime) {}
}

Which one is the best approach? (design-wise and performance-wise)

Subscribing something to the OnUpdate action (and not inheriting the Game class), or inheriting the Game class and overriding the virtual method?


Solution

  • This depends on who the target audience is for the Update notification. If it's for only derived classes then a virtual method is a fine approach. If it's for derived classes and or arbitrary consumer then the event style pattern is the correct approach.