I have one base class that is used to declare generic data structures that have a fixed length in a datablock:
public abstract class FixedLengthDataItem
{
// a static field here to store the fixed length?
public sealed void LoadFromBytes(byte[] data)
{
// Check the fixed length here
DoStuff(data, offset);
}
protected abstract void DoStuff(byte[] data);
}
There can be a lot of data structures that have a fixed length and my intent is to describe them in subclasses.
I'd like to know whether there is a possibility to transmit the information about the fixed length when declaring the inheritance in the child classes:
public class ChildClass : FixedLengthDataItem // Specific syntax here?
{
public override void DoStuff(byte[] data)
{
// Some stuff
}
}
I cannot find a syntax like : FixedLengthDataItem(2)
or : FixedLengthDataItem<2>
that would allow to set the value of a static field that would be declared in the mother class and could be used to "generically" check the length in the LoadFromBytes
method (2 in my example).
If there is no way to do it, what could be a smart way to allow anyone to write subclasses making sure that the check that is performed in the LoadFromBytes
method checks the right thing?
I thought about something like:
private readonly int _size;
protected FixedLengthDataItem(int size) { _size = size; }
in the base class. And:
public ChildClassFoo() : base(2) { } // or
public ChildClassBar() : base(3) { } // etc.
in the child class(es). But doing this:
- a constructor must be declared in each derived class,
- more important: a field
size
will exist in each object whereas the same size applies for all the instances of each derived class which is not very wise I guess.