Search code examples
enumsmql4mql5

Can an Enum have its own method in MQL4/MQL5. Can i store string in an Enum as a value?


I am trying to write a code where i would like to use ENUM as a class and call some method on it.. For example toString(). Or can i store a string value in an Enum in Mql4/Mql5 language?


Solution

  • No an enum cannot have methods. You can, however, use polymorphic behavior to mimic this desired attribute.

    #property strict
    #property script_show_inputs
    #include <Object.mqh>
    //+------------------------------------------------------------------+
    enum ENUM_STRAT {STRAT1, STRAT2};
    //+------------------------------------------------------------------+
    input ENUM_STRAT  inpStrategy=STRAT1;
    //+------------------------------------------------------------------+
    class StrategyBase : public CObject
    {
       public: virtual string toString()=0;  
    };
    //+------------------------------------------------------------------+
    class Strategy1 : public StrategyBase
    {
       public: virtual string toString() override { return "Strategy #1"; }
    };
    //+------------------------------------------------------------------+
    class Strategy2 : public StrategyBase
    {
       public: virtual string toString() override { return "Strategy #2"; }
    };
    //+------------------------------------------------------------------+
    StrategyBase* initStrategy()
    {
       switch(inpStrategy)
       {
          case STRAT1:
             return new Strategy1();
          default:
             return new Strategy2();
       }
    }
    //+------------------------------------------------------------------+
    //| Script program start function                                    |
    //+------------------------------------------------------------------+
    void OnStart()
    {
       StrategyBase *strategy = initStrategy();
       printf("The result of the toString() method is %s", strategy.toString());
       delete strategy;
    }