2

I am implementing a Matrix class with generics in order to have the ability to create objects of different types, like:

 Matrix<double> A = new Matrix<double>(10,20);
 Matrix<int> B = new Matrix<int>(10,20);
 Matrix<Complex> C = new Matrix<Complex>(14,25);

The basic class scheme is the following:

public class Matrix<T> : IFormattable, IEquatable<T>, IComparable 
  where T : struct, IEquatable<T>, IFormattable
{
    T[] _data { get; set; }

    public int columns;

    public int rows;

    // ...
}

As I have implement the generic class of the above objects as also constructors and basic methods for parsing or iterating through the objects, everything works fine.

At this point I am trying to implement basic arithmetic operations on the above generic Matrix objects. And starting from the summing process I face the problem that I cannot implement addition in T objects (The base of the matrix is a T[] object). So when I sum the at two T objects while indexing them seems to give me an expected error that i cannot overcome. As an example I want the following code to Sum the elements of two matrices:

for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < columns; j++)
    {
        //Operator '+' cannot be applied to operands of type 'T' and 'T'
        C[i, j] = B[i,j] + this[i, j]; 
    }
}

I tried to overcome the above problem with several solutions I found on the internet but I didn't come up to a solution!

Is there any efficient solution for this? As creating a method for the call at the case type of T is double or int etc? Any help will be really appreciated. Thanks in advance!

Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
lostpfg
  • 31
  • 2
  • 4
  • You would have to add the logic per type i.e. check if it is a known type like int or double and then calculate by casting. A maybe better approach would be to create a specialized inherited class (e.g. `class IntMatrix : Matrix`) and implement the logic there. – Manfred Radlwimmer Oct 19 '17 at 11:04
  • 1
    https://stackoverflow.com/questions/32664/is-there-a-constraint-that-restricts-my-generic-method-to-numeric-types – Miguel A. Arilla Oct 19 '17 at 11:05
  • This might help too: https://stackoverflow.com/questions/3016429/reflection-and-operator-overloads-in-c-sharp – Manfred Radlwimmer Oct 19 '17 at 11:12
  • I'd say the most _convenient_ solution would be to use [this approach](https://stackoverflow.com/a/8122675/175070) to build a callback for each operator. You could store each one in a `static readonly` field in your `Matrix` class, since static fields are scoped to a specific generic instantiation. That way, you'd only build each callback once per type `T`. – Mike Strobel Oct 19 '17 at 11:57
  • @MikeStrobel That's one of the linked dupes – DavidG Oct 19 '17 at 11:58

0 Answers0