Having trouble with extension methods for byte arrays

Posted by Dave on Stack Overflow See other posts from Stack Overflow or by Dave
Published on 2010-04-05T13:58:43Z Indexed on 2010/04/05 14:03 UTC
Read the original article Hit count: 470

Filed under:
|
|

I'm working with a device that sends back an image, and when I request an image, there is some undocumented information that comes before the image data. I was only able to realize this by looking through the binary data and identifying the image header information inside.

I've been able to make everything work fine by writing a method that takes a byte[] and returns another byte[] with all of this preamble "stuff" removed. However, what I really want is an extension method so I can write

image_buffer.RemoveUpToByteArray(new byte[] { 0x42, 0x4D });

instead of

byte[] new_buffer = RemoveUpToByteArray( image_buffer, new byte[] { 0x42, 0x4D });

I first tried to write it like everywhere else I've seen online:

public static class MyExtensionMethods
{
  public static void RemoveUpToByteArray(this byte[] buffer, byte[] header)
  {
    ...
  }
}

but then I get an error complaining that there isn't an extension method where the first parameter is a System.Array. Weird, everyone else seems to do it this way, but okay:

public static class MyExtensionMethods
{
  public static void RemoveUpToByteArray(this Array buffer, byte[] header)
  {
    ...
  }
}

Great, that takes now, but still doesn't compile. It doesn't compile because Array is an abstract class and my existing code that gets called after calling RemoveUpToByteArray used to work on byte arrays.

I could rewrite my subsequent code to work with Array, but I am curious -- what am I doing wrong that prevents me from just using byte[] as the first parameter in my extension method?

© Stack Overflow or respective owner

Related posts about c#

Related posts about extension-methods