DaveD wrote:
Can anyone help me get this compiled ?
void Write<T>(T val) {
byte[] bytes = BitConverter.GetBytes(val);
Array.Reverse(bytes);
writer.Write(bytes);
}
The problem is that for T=bool, BitConverter.GetBytes(bool) won't
compile.
It won't compile for any T. The only .GetBytes() overload that can legally
be invoked for a generic T would take a parameter of Object type, but
there's no such overload.
In C++ I would have created an explicit instantiation like this
void Write<bool>( bool val ) { writer.Write((byte)(val?
1:0)); } //
I know that we don't have this capability in C#, so any other ideas
welcome please.
The most straightforward way, tedious as it is, is to write out the
overloads yourself:
void Write(byte[] val) {
Array.Reverse(val);
writer.Write(val);
}
void Write(bool val) {
Write(BitConverter.GetBytes(val));
}
void Write(int val) {
Write(BitConverter.GetBytes(val));
}
Etcetera, etcetera. Even though all functions are "the same", they're not
really. C++ templates can exploit textual similarity, C# generics cannot.
As others have suggested, reflection is an option here (getting the proper
overload for .GetBytes()) dynamically) but I wouldn't bother. The resulting
code will be slower and certainly not clearer, even if it might be somewhat
shorter. If you take the step of optimizing the reflection (through
lightweight code generation for example) the code becomes even more unclear,
and might actually end up longer.
--
J.