0

I made this method in a generic class. I want to sum two matrices if the type is ? Because the compiler says the "'+=' operator cannot be applied to operands type 'T' and 'T'".

Here's the code:

public static Matrix<T> operator +( Matrix<T>m1, Matrix<T>m2)
        {
            if(m1.Length!=m2.Length)
            {
                throw new MatrixSizeMisMatchException("different size");
            }
            if(m1.GetType()!=m2.GetType())
            {
                throw new MatrixDifferentTypeException("type mismatch");
            }
            for(int i=0;i<m1.Length;++i)
            {
                for(int j=0;j<m1.Length;++j)
                {
                    m1[i,j] += m2[i,j];// And here's the problem
                }
            }
        }

The Length attribure is same for all matrices, because I work only 'NxN' matrices.

  • This would assume your type `Matrix` can use `+=` on itself. How do you guarantee that? What if I pass `MyClass` to it, how will you interpret `Matrix + Matrix`? – Jeroen Vannevel May 01 '14 at 20:23
  • I see what you think, but at the class declaration I used "where" keyword and the following interfaces:IComparable, IComparable, IConvertible, IEquatable, IFormattable. Of course if your class effectuate these interfaces, then it can make some problem, but I don't know better way to filter to numeric types. – user3593615 May 01 '14 at 20:28
  • For a constraint on numeric types I'll redirect you to [my answer here](http://stackoverflow.com/a/22425077/1864167). I think it will also solve the problem you have here. – Jeroen Vannevel May 01 '14 at 20:29

0 Answers0