0

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!

liszt
  • 1,139
  • 1
  • 9
  • 17
  • possible duplicate of [Generic method with multiple constraints](http://stackoverflow.com/questions/588643/generic-method-with-multiple-constraints) – Ehsan Sajjad Jul 20 '15 at 17:33
  • @EhsanSajjad No, note that I have only one type parameter. – liszt Jul 20 '15 at 17:35

1 Answers1

3

This is the best you're going to do:

abstract class BArray<T>
{
    byte[] Encode();
    T[] Decode(byte[] bytes);
}

class BArrayInt : BArray<int> { ... }
class BArrayDouble : BArray<double> { ... }
...

static class BArray
{
    public static BArray<int> Create(int[] values)
    {
        return new BArrayInt(values);
    }
    public static BArray<double> Create(double[] values)
    {
        return new BArrayDouble(values);
    }
    ...
}

Each of the BArray* classes provides an implementation of Encode and Decode. A user of the BArray<T> class just writes BArray.Create(values) and it will work for values of types int[], double[], etc. you define.

Timothy Shields
  • 75,459
  • 18
  • 120
  • 173
  • 3
    @EhsanSajjad It actually will work exactly as the asker wants in practice. The only difference is that instead of writing `new BArray(values)` you have to write `BArray.Create(values)`. – Timothy Shields Jul 20 '15 at 17:37
  • I'm thankful for the answer, and yet saddened that C# doesn't allow a cleaner (i.e. more beautiful, to me) solution. Oh well, at least it works! – liszt Jul 22 '15 at 01:36