The reason I "require" or prefer using a Value type in my case rather than sticking with the direct reference type required, is because a struct is being used as a Dictionary's key, and this was already the case before I added a reference type field into the struct. At this point, the dictionary's keys are being passed around in many areas with a simple =
reassignment with the intention of being a copy of all the struct's values with no reference shenanigans. This is particularly important in the case of being a Dictionary key, where the keys should be unique, but also should be equal/copied when passing them around to eventually re-query the dictionary using the copied value.
With that said, is there some merit to breaking down reference types used into their primitive values in order to avoid the struct being a reference type, or would it be more advisable to simply create some kind of deep-copy function and ensure we are using that for all reassignments?
Here is an example struct where I'm having this issue, and an example struct with my described solution:
// This struct contains a reference type property, so can't directly be copied with = reassignment,
// would have to create a deep-copy function for reassignment and only use that.
struct MyReferenceStruct
{
private const int MY_REF_PROPERTY_EXPECTED_LENGTH = 8; // myRefProperty has an expected, consistent byte length
int myValProperty; // value type - no reference issues
byte[] myRefProperty; // byte[] is a reference type! We cannot copy this struct using = reassignment
}
// this struct only contains value types, so it can be easily copied with = reassignment
struct MyValueStruct
{
// will still be used to validate the byte[] before converting it to a long
private const int MY_REF_PROPERTY_EXPECTED_LENGTH = 8; // myRefProperty has an expected, consistent byte length
int myValProperty; // value type - no reference issues
// value type - no reference issues
// myRefProperty is supposed to have a consistent byte length of 8 bytes, so we could instead
// save the data as 8 individual byte properties, or more concisely, 1 long/Int64 (we will
// make sure to have consistent endianness when making this conversion)
long myValProperty2;
}
This is more of a discussion post where I already know of two working solutions:
- Keeping the struct as a reference-type and using a deep-copy function for reassignment
- Breaking down reference types into their value types in order to keep the struct as a value-type
I am curious to hear thoughts on what is the better approach in this situation. I personally prefer breaking down the reference types, so that I don't have to remember to use a deep copy function when reassigning/copying this struct, and won't have to hunt down all the existing copy-reassignments.