0

I am using a method from an external library, with the following prototypes:

void ReadRaster(byte[] vals);
void ReadRaster(float[] vals);
void ReadRaster(int[] vals);

In order to interface with that function, I was thinking on implementing a generic method such as

void OpenImage<PixelType>(int x, int y) {

    // Lots of code
    (...)

    var pixels = new PixelType[x * y];
    ReadRaster(pixels);

    // More code
    (...)
}

However, this won't do because I would have to limit PixelType to int, float or byte.

How could I do this?

manatttta
  • 3,054
  • 4
  • 34
  • 72
  • 2
    How does PixelType become `byte[]`, `float[]` or `int[]`? – ProgrammingLlama Nov 29 '17 at 08:57
  • See https://stackoverflow.com/questions/32664/is-there-a-constraint-that-restricts-my-generic-method-to-numeric-types – Dylan Nicholson Nov 29 '17 at 08:57
  • 3
    In short - you can't. – Evk Nov 29 '17 at 09:00
  • why closed as duplicate? I was going to answer... ok the key is you have to share your _lots of code_ among 3 overloads using a method. you can also use enum of members `IntType, FloatType, ByteType` and with strategy pattern do your logic with minimum code – M.kazem Akhgary Nov 29 '17 at 09:02
  • Imagine if it was the other way around - and the external library would have `ReadRaster()` methods for arrays of _all_ types - it still would not compile as `ReadRaster()` is not a generic method and the correct overload needs to be known at compile time. – C.Evenhuis Nov 29 '17 at 09:05
  • @M.kazemAkhgary If you have an answer, answer the duplicate, and not this one. – Patrick Hofman Nov 29 '17 at 09:13
  • This is a terrific solution, which you can use even with lots of shared code: https://stackoverflow.com/a/22425077/993547. – Patrick Hofman Nov 29 '17 at 09:14

0 Answers0