I need a small datatype that has exactly X bytes.
To archive this I have basically two ways:
I have seen that in a lot of structs f. e. Guid or MongoDb's ObjectId concrete fields are used, even if they are more or less just a plain byte array.
public struct XY
{
private readonly int _a;
private readonly int _b;
private readonly int _c;
}
vs.
public struct XY
{
private readonly byte[] bytes = new byte[12]; // probably set via ctor
}
Does this provide any significant benefits (apart from usability)?
Or to put it in another way: Is using a byte array within a struct a bad idea?
The reason plain fields are most commonly used in structs is that they will be stored as part of the struct. So if I have an Guid[], then all the data will be stored in a single contiguous memory block. And this have benefits with regards to data locality and memory usage.
If you store an array your struct will only contain a single reference, while the actual data will be stored elsewhere, and accessing the data needs an indirection. That does not mean you should never store arrays as part of a struct, but it is most beneficial if you need data that is varying in size, or some other special need.
For small fixed size data, using individual fields is probably preferable. If you want to treat the fields as a sequence of values you can always implement IEnumerable/IReadOnlyCollection/IReadOnlyList.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With