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
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.