473,385 Members | 1,834 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Help with generic method definition containing BitConverter.GetBytes

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. 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. I can't see a "where" constraint that will work for
me, unless I create my own wrapper classes (don't go there please!).

Thanks and regards
Dave Dawkins
Sep 2 '08 #1
5 5921
DaveD <da***********@gmail.comwrote:
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. In C++ I would have created an explicit instantiation like
this

void Write<bool>( bool val ) { writer.Write((byte)(val?
1:0)); } //
As far as I'm aware in C++ you wouldn't have really needed to, as the
templating system would have taken care of it for you.
I know that we don't have this capability in C#, so any other ideas
welcome please. I can't see a "where" constraint that will work for
me, unless I create my own wrapper classes (don't go there please!).
No, basically there's no way of doing this with .NET generics. There's
a big difference between .NET generics (where the generic method/type
resolves all calls including overloads at compile-time) and C++
templates (which are sort of very smart macros in many ways).

Sorry, but it can't be done. You could use reflection of course, and
that can be optimised in various ways to reduce the performance penalty
significantly, but it will still be slightly "icky".

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Sep 2 '08 #2
This problem isn't well suited to generics. You could use reflection,
but that will be slow unless you use Delegate.CreateDelegate (and
cache it). I wonder if overloads wouldn't be more suitable than
generics here?
Sep 2 '08 #3
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.
Sep 3 '08 #4
One other thought... would I be correct in assuming that you are
trying to correct for endianness?

Note that Jon has an EndianBitConverter in his MiscUtil library that
might be useful:

http://www.pobox.com/~skeet/csharp/miscutil/

Marc
Sep 3 '08 #5
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. 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. I can't see a "where" constraint that will work for
me, unless I create my own wrapper classes (don't go there please!).
Use generics at class level, so you can have per-type fields.

Then have a field of delegate type Converter<T, byte[]>. You can then
assign a different implementation for each T. BitConverter.GetBytes can be
used for those T where they are appropriate, you will still need to
explicitly assign the delegate field for each T separately.

>
Thanks and regards
Dave Dawkins

Sep 3 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Charles Law | last post by:
I want to do something like this: obj = CType(value, Value.Type) Well, not exactly, but I think that captures the essence. I realise it won't work as I have written it, and it looks a bit like...
1
by: Sisnaz | last post by:
I'm sending a message from VB.net (2003) to a C++ app via TCP sockets of values 1 to 328. The message is a WORD value where I have to manage both bytes for the WORD. I'm sending and receiving data...
36
by: Cap'n Ahab | last post by:
I have used VB3 - VB6, so learning all this OO stuff is reasonably new to me (although I looked at Java a few years ago). Anyway, I thought I would write a small class to begin with, with a...
1
by: intrader | last post by:
I have a .NET interop assembly Hash.MD5Sum with two methods Identity and GetMD5Sum. I want to call the methods from ASP (JScript), The debugger tells me that object oMD5Sum has one the ToString()...
2
by: intrader | last post by:
I have a .NET interop assembly Hash.MD5Sum with two methods Identity and GetMD5Sum. I want to call the methods from ASP (JScript), The debugger tells me that object oMD5Sum has only one method...
3
by: Anatoli Koutsevol | last post by:
Is there some way to determine size in bytes for a type parameter T in generic class cls<T>. For instance, I need some generic way to covert T array to an array of bytes and conversely, as in...
9
by: TechN00b | last post by:
I'm trying to write a quick commandline app that takes a string from the commandline and returns a formatted md5 hash. Unfortunately the code won't comple and returns an error of "No accessible...
4
by: Yasin Cepeci | last post by:
I ve get float data from serial port. I ve taken it in the form of hex by modbus protocol. I know it is float but I couldnt convert it there is a few sample data below; B3 33 43 34 = 180.699997...
1
by: DR | last post by:
mySqlBytes.buffer is getting converted to BigEndian even though both SQL server 2005 and the CLR function are on the same machine which shows BitConverter.IsLittleEndian == true in tsql: select...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.