I'm trying to pass a value constrained type to BitConverter.GetBytes, but c# only permits a struct constraint. For example:
private void writePrimitive<T>(T obj) where T : struct {
if (!typeof(T).IsPrimitive)
throw new ArgumentException("Only primitive types allowed");
Buffer.BlockCopy(BitConverter.GetBytes(obj), 0, buf, pos, sizeof(obj));
update(sizeof(obj));
}
The compiler understandably borks at this. Still I'd like to find a solution that avoids repetition and doesn't require writing multiple overloads for different primitives.
Question
simplezz
Hi all,
I'm trying to pass a value constrained type to BitConverter.GetBytes, but c# only permits a struct constraint. For example:
The compiler understandably borks at this. Still I'd like to find a solution that avoids repetition and doesn't require writing multiple overloads for different primitives.Link to comment
Share on other sites
2 answers to this question
Recommended Posts