I need to get the size of variables I'm using to write them to a byte array. However I wish to retain easy refactoring so using something like sizeof(int)
doesn't really cut it.
This is a simplified version of what I have now:
public byte[] ToBytes()
{
int byteIndex = 0;
byte[] result = new byte[sizeof(byte) + sizeof(byte) + sizeof(long) + RawBytes.Count];
...
BitConverter.TryWriteBytes(new Span<byte>(result, byteIndex, sizeof(long)), TimeStamp)
byteIndex += sizeof(long);
...
return result;
}
Where TimeStamp
is a property of the long
type.
If I want to change the type of the TimeStamp
variable I now need to modify three parts of this code.
As I add more variables it will be even easier to make a mistake.
And it's also not very clear which variable each sizeof()
refers to.
Is there a simple solution? Something like sizeof(typeof(TimeStamp))
Or do I need to make a workaround like writing my own sizeof-method with an overload for each type or an is
check for each type I want to use?
Though not an answer to my question, @HansPassant suggested using a BinaryWriter
and writing to a MemoryStream
which will solve the problem at hand.