Generic types: Ensuring the existance of multiplication

I've finally started reading up on generics. Now I'm trying to implement a generic Matrix<T> class. I've got the basics - I store elements in a two-dimensional array and i've provided an indexer to access individual elements.
I want to implement matrix multiplication, so I need to limit the types that this class can accept to ones that define multiplication. My idea was to use a constraint on T(an interface of some sort), but I couldn't find one that would ensure that T has multiplication. Any idea how to achieve this
Also, it would be really cool if I could actually instantiate a Matrix to hold any type (for example, strings), but only allow to perform multiplication if T was a numeric type. I have a feeling that this is impossible to achieve using one generic class, but if that's possible - I would like to know.



Answer this question

Generic types: Ensuring the existance of multiplication

  • Holiday

    There's no constraint that you can impose to ensure that T supports the multiplication operator * or any other operator.

    One option would be to use delegates:

    So, we need a binary operator:

    delegate T BinaryOp<T>(T x, T y);

    and we have a Matrix generic class:

    class Matrix<T>

    with a method

    Matrix<T> Multiply(Matrix<T> m, BinaryOp<T> mulOp)

    now where you need the * operator you will can write

    a = mulOp(b, c);

    instead of

    a = b * c;

    Next you need to call the Multiply method of the Matrix<T> class:

    we need a method that does that multiply operation (in another class), let's say we're interested in Matrix<double>:

    double DoubleMulOp(double x, double y)

    {

    return x * y;
    }

    and now we are ready to multiply 2 matrices:

    Matrix<double> A = new Matrix<double>();

    Matrix<double> B = new Matrix<double>();

    A = A.Multiply(B, DoubleMulOp);

    Note the use of the DoubleMulOp method name as the second name for the Multiply method.

    Now don't ask me about performance implications... I did not tested it


  • YCT

    Yip, it sounds as if you want to constrain T to types that implement a certain operator (* in your case)... this is not done for C# 2.0, but would be really valuable!

    You could probably work around this by implementing some custom interfaces (IMultipliable !) but it's not as elegant as operator constraints could have made it.



  • Marcelo Paiva

    Ronzy –

    What you’re trying to do can’t be done in C# 2.0



  • Generic types: Ensuring the existance of multiplication