I'm writing a generic DataStructure<T>
which persists on the disk, and I need to write it such that T
is guaranteed to be serializable in a fixed number of bytes. For example, int
and char
should be accepted, but string
or int[]
should not be. Likewise, a struct
with a string
member is not acceptable, but an unsafe struct
with a fixed char
array is.
I could write a runtime test in the initializer using reflection and sizeof
to test each member, but that seems like a terrible hack. Is there any efficient and (relatively) safe way to do this?
There is no way to statically support a generic parameter which only have a fixed specific size. Constraints are limited to interfaces, ref / struct, base class and new
.
What you can do though is use static factory methods to limit the uses of the generic to a known finite set of types which are suitable. For example
class DataStructure<T> {
private DataStructure(T value) {
...
}
}
static class DataStructure {
public static DataStructure<int> Create(int i) {
return new DataStructure<int>(i);
}
public static DataStructure<char> Create(char c) {
return new DataStructure<char>(c);
}
}
This is limiting though because it requires you to list all comparable types ahead of time. If you want a more flexible solution that works with user defined types you'll need to implement a runtime check.
public static DataStructure<T> Create<T>(T value) {
RuntimeVerification(typeof(T));
return new DataStructure<T>(value);
}
Every valuetype that directly or indirectly contains only value types, but no reference types has a limited size. The only way to test that is at runtime using reflection.
If that is a good idea is a different question, and I'd say it's not a good idea. Serializing the raw data of a type is generally a bad idea IMO.
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