I am storing data with different formats and lengths. I have a class hierarchy to represent this:
abstract class BaseDataFormat{
abstract void InitalizeFromBytes(byte [] );
}
class DataFormat1 : BaseDataFormat{...} // data stored in 3 bytes
class DataFormat2 : BaseDataFormat{...} /// data stored in 4 bytes
When I am reading my data (say from a byte []), I need to know the length (# of bytes) to read and create the corresponding type appropriately. DataFormat1 and DataFormat2 have different lengths, so how do I get this information at runtime? ie.
Fcn<DATAFORMATTYPE>(...)
where DATAFORMATTYPE: BaseDataFormat, new();
{
DATAFORMATTYPE tmp = new DATAFORMATTYPE();
tmp.InitalizeFromBytes(ReadFromByteBuffer( ... someLength));
}
How do I encode the proper # of bytes to read based on the DATAFORMATTYPE? The length for each feels like it should be a static property of the data format type, but static properties cant be overriden by the derived class, so I am not sure how to do this.
The length can be coded as an instance property, but this seems like it should be knowledge encoded at the class level(ie. static). Is there a design pattern to solve this?
Thanks
Perhaps have a property in
BaseDataFormatcalledDataLength. To force all inheritors to set a value, take the length in atBaseDataFormat‘s constructor, and then set that property to the data length.Example:
Granted, it’s not at the static level, but it is something that is forced for all inheritors.
Another way is as how VirtualBlackFox suggested, decorate the class with an attribute. The only problem is that AFAIK you can’t force attributes onto a class, like with abstract members.