I am currently developping a library for a binary application protocol. The following code sample does not compile (static methods definition not allowed in abstract type. Too bad :(), but shows my intention :
public abstract class CmdBody<T>
{
public static abstract byte[] ToBytes(T cmdBody);
public abstract int GetLength();
}
public class CmdBodyA : CmdBody<CmdBodyA>
{
static override byte[] ToBytes(CmdBodyA cmdBody)
{ // Implementation }
}
public class CmdBodyB : CmdBody<CmdBodyB>
{
static override byte[] ToBytes(CmdBodyB cmdBody)
{ // Implementation }
}
[...]
public class Cmd<T>
{
public CmdHeader Header { get; set; }
public CmdBody<T> Body { get; set; }
public byte[] ToBytes()
{
byte[] cmdBytes = new byte[Header.GetLength() + Body.GetLength()];
Header.ToBytes().CopyTo(cmdBytes, 0);
Body.ToBytes().CoptyTo(cmdBytes, Header.GetLength());
return cmdBytes;
}
}
So pretty basic stuff, a Cmd consists of an Header and a Body, Header type being common to all Cmd(s) and Body having different parameters (properties) depending of the Cmd type, and I would like to work with Cmd objects, and to be able to call ToBytes() on them to send them over the network.
In my real implementation I am using conversion operator instead of ToBytes() method, but I wanted to keep the code sample simple, at the end it does the same job.
I have many different command types, and I can't work out a solution to keep it simple and achieving what I want with just a single generic Cmd type. The only solution I can think of would be to get rid of the static method in the base CmdBody class, get rid of the generic aspect and for each CmdBody type make an associated Cmd class (class CmdA, class CmdB ...) but this will incur a lot of code duplication at the end of the day.
Any idea for a nice desing to help me work arround this ?