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!