Having trouble with extension methods for byte arrays
- by Dave
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?