I have a class describing an array that can be serialized to a custom binary format and back. This array has a single type parameter specifying its values which can be int
, double
or bool
. I want to write something like this:
class BArray<T> where T: int, double, bool {
BArray(T[] values) { ... }
byte[] Encode() { ... }
T[] Decode(byte[] bytes) { ... }
...
}
I know this doesn't compile, but is there a way to do it? If no, what would be the best way to go about doing something close to this? In essence, I need different behaviour for the Encode
and Decode
methods depending on the array values' type. In addition, I want the class user not to have to worry about the differing implementations, i.e. the following should work:
var ints = new int[] { 1, 2, 3 };
var intB = new BArray(ints);
var dbls = new double[] { 3, 4 };
var dblB = new BArray(dbls);
But using an unimplemented type should fail:
var strs = new string[] { "this", "should", "fail" };
var strB = new BArray(strs); // TYPE ERROR!
Thanks!