Link to home
Start Free TrialLog in
Avatar of deleyd
deleydFlag for United States of America

asked on

Beginner: combining two nearly identical classes?

How can I combine these two nearly identical classes?
  class MyMsgAAA
  {
    private int msglen = 0;
    private byte[] MyMsg = new byte[500];

    /*constructor*/
    public MyMsgAAA(byte[] ba)
    {
      //Now build the message
      this.add(0x01);
      ...
      add some bytes special to AAA messages
      ...
      //message itself (.add escapes any special bytes)
      for (int i = 0; i < ba.Length; i++)
      {
        this.add(ba[i]);
      }
    }


    /* THE REST HERE IS IDENTICAL */
    public void add(byte b)
    {
      MyMsg[msglen++] = b;
    }
    //Return message
    public byte[] msg
    {
      get
      {
        byte[] target = new byte[this.msglen];
        Array.Copy(MyMsg, target, msglen);
        return target;
      }
    }
  }

Open in new window

  class MyMsgBBB
  {
    private int msglen = 0;
    private byte[] MyMsg = new byte[500];

    /*constructor*/
    public MyMsgBBB(byte[] ba)
    {
      //Now build the message
      this.add(0x01);
      ...
      add some bytes special to BBB messages
      ...
      //message itself (.add escapes any special bytes)
      for (int i = 0; i < ba.Length; i++)
      {
        this.add(ba[i]);
      }
    }


    /* THE REST HERE IS IDENTICAL */
    public void add(byte b)
    {
      MyMsg[msglen++] = b;
    }
    //Return message
    public byte[] msg
    {
      get
      {
        byte[] target = new byte[this.msglen];
        Array.Copy(MyMsg, target, msglen);
        return target;
      }
    }
  }

Open in new window

In general, I want to call
MyMsgXXX(various parameters)

Open in new window

If the parameter types were always different I could just make different constructors for the same class. But what if some messages have the same type of parameter (such as in example above)?
Avatar of kaufmed
kaufmed
Flag of United States of America image

I would say make a common base class which encapsulates the common functionality. You can provide specialized constructors in each child if need be.
Avatar of deleyd

ASKER

Example?
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of deleyd

ASKER

:)