• 0

Buffer.BlockCopy Passing Generic Argument


Question

Hi all,

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.

2 answers to this question

Recommended Posts

  • 0

A common technique to get around the limitations of generic constrains is to parameterize the non-generic functions you want to use. So:

        private void writePrimitive<T>(Func<T, byte[]> getBytes, T obj) {
            byte[] bytes = getBytes(obj);
            Buffer.BlockCopy(bytes, 0, buf, pos, bytes.Length);
            update(bytes.Length);
        }
       
        // Usage:
        writePrimitive(BitConverter.GetBytes, 3);
        writePrimitive(BitConverter.GetBytes, true);

Can't get around having to repeat BitConverter.GetBytes, but that's about as good as it gets I think. Type inference figures out what overload to call based on the type of the second parameter.

  • 0
  On 25/07/2015 at 02:22, Andre S. said:

A common technique to get around the limitations of generic constrains is to parameterize the non-generic functions you want to use. So:

        private void writePrimitive<T>(Func<T, byte[]> getBytes, T obj) {
            byte[] bytes = getBytes(obj);
            Buffer.BlockCopy(bytes, 0, buf, pos, bytes.Length);
            update(bytes.Length);
        }
       
        // Usage:
        writePrimitive(BitConverter.GetBytes, 3);
        writePrimitive(BitConverter.GetBytes, true);

Can't get around having to repeat BitConverter.GetBytes, but that's about as good as it gets I think. Type inference figures out what overload to call based on the type of the second parameter.

Perfect. Thanks Andre.

A delegate also worked for the read back function. 

This topic is now closed to further replies.
  • Posts

    • It's Intel-based, but I configured one of these yesterday with a Snapdragon X processor and found that it heats up just as much as Intel processors. There's no point in using a Snapdragon X processor unless it's fanless, like the Snapdragon 8cx.
    • Good stuff Brave. Hopefully MS respects user choice with this. They don't have a great track record but time will tell.
    • Yes. A search on Bing would have explained it.
    • As someone who regularly has to go through the OOBE for the Mini PCs I review, I can confirm that this "Windows Update failed" thing happens even on newly installed systems. I had it last week until I left it on overnight and only then did it somehow magically fix itself and applied the update, this was after wasting a full day of resetting, clearing Windows Update cache (following Microsoft recommendations). Microsoft needs to stop this BS of releasing (at best) beta quality features and updates. They need to go back to using Patch Tuesday for bugs and security fixes, and annual Service Packs to introduce fully tested new features into the OS. The 21H1, 21H2, 22H2, 23H2, 24H2 style updates are just a poor excuse of rolled up features released up to and in between these updates, and even then some of the announced features don't get enabled for end users? What is preventing my 24H2 AMD 9950X3D, X870E system from displaying the Phone Link panel in the Start menu, for example?
    • RIP Prince... for over 50 years you entertained us, brought us musicians that wowed the masses... you brought us into your home, your world and your loving insanity for life itself. You'll never be truly gone, because you'll be with us for the rest of our own lives.
  • Recent Achievements

    • Week One Done
      SmileWorks Dental earned a badge
      Week One Done
    • Community Regular
      vZeroG went up a rank
      Community Regular
    • Collaborator
      Snake Doc earned a badge
      Collaborator
    • Week One Done
      Snake Doc earned a badge
      Week One Done
    • One Month Later
      Johnny Mrkvička earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      583
    2. 2
      Michael Scrip
      199
    3. 3
      ATLien_0
      196
    4. 4
      +FloatingFatMan
      129
    5. 5
      Xenon
      123
  • Tell a friend

    Love Neowin? Tell a friend!