I am writing code that interfaces with an external API that I cannot change:
public class ExternalAPI
{
public static void Read(byte[] buffer);
public static void Read(int[] buffer);
public static void Read(float[] buffer);
public static void Read(double[] buffer);
}
It's important that I call the correct overloaded method when reading data into buffer
, but once the data is read in, I will process it generically. My first pass at code that does that was:
public class Foo<T>
{
T[] buffer;
public void Stuff()
{
ExternalAPI.Foo(buffer);
}
}
C#, though, won't convert from T[]
to byte[]
. Is there a way to enumerate the types that T
can represent explicitly? I've tried using a where T :
clause, but there doesn't appear to be a way to say where T : {byte, int, float, double and nothing else ever}
?
Following the advice here: Generic constraint to match numeric types, I added constraints to the generic, and also added a generic method to my simulated API that takes an object
as its parameter
public class ExternalAPI
{
public static void Read(object buffer);
public static void Read(byte[] buffer);
public static void Read(int[] buffer);
public static void Read(double[] buffer);
}
public class Foo<T> where T: struct, IComparable, IComparable<T>, IConvertible, IEquatable<T>, IFormattable
{
T[] buffer;
public void Stuff()
{
ExternalAPI.Read(buffer);
}
}
This will compile and run happily, but the only method that is ever called is Foo(object buffer)
, even when T
is byte
. Is there a way to force methods of non-generic classes to use the most specific overload when the calling class is generic?