Generic that takes only numeric types (int double etc)?

Posted by brandon on Stack Overflow See other posts from Stack Overflow or by brandon
Published on 2011-01-06T22:10:21Z Indexed on 2011/01/07 5:54 UTC
Read the original article Hit count: 191

Filed under:

In a program I'm working on, I need to write a function to take any numeric type (int, short, long etc) and shove it in to a byte array at a specific offset.

There exists a Bitconverter.GetBytes() method that takes the numeric type and returns it as a byte array, and this method only takes numeric types.

So far I have:

    private void AddToByteArray<T>(byte[] destination, int offset, T toAdd) where T : struct
    {
        Buffer.BlockCopy(BitConverter.GetBytes(toAdd), 0, destination, offset, sizeof(toAdd));
    }

So basically my goal is that, for example, a call to AddToByteArray(array, 3, (short)10) would take 10 and store it in the 4th slot of array. The explicit cast exists because I know exactly how many bytes I want it to take up. There are cases where I would want a number that is small enough to be a short to really take up 4 bytes. On the flip side, there are times when I want an int to be crunched down to just a single byte. I'm doing this to create a custom network packet, if that makes any ideas pop in to your heads.

If the where clause of a generic supported something like "where T : int || long || etc" I would be ok. (And no need to explain why they don't support that, the reason is fairly obvious)

Any help would be greatly appreciated!

Edit: I realize that I could just do a bunch of overloads, one for each type I want to support... but I'm asking this question because I want to avoid precisely that :)

© Stack Overflow or respective owner

Related posts about c#