I am writing a class library in C# for working with matrices, and am currently working on a subclass of Matrix called ComplexMatrix. The Matrix base class works with values of the Int32 data type (a more advanced version uses Double), and the ComplexMatrix of the System.Numerics.Complex structure (.NET 4).
For the base class, I overrode ToString() as:
| 1 2 |
| 3 4 | printed as {{1,2}{3,4}}
The System.Numerics.Complex structure overrides ToString() in the form:
a+bi printed as (a,b) where a is real and b is imaginary
When overriding ToString in ComplexMatrix, I simply used the method:
public override string ToString()
{
return base.ToString();
}
Unfortunately, for a complex matrix, the following occurred:
| 1+1i 1+2i |
| 2+1i 2+2i | printed as {{0,0}{0,0}} rather than {{(1,1),(1,2)}{(2,1)(2,2)}}
The original ToString() code I wrote for the Matrix class is:
public override string ToString()
{
StringBuilder matrixString = new StringBuilder();
string comma = "";
matrixString.Append("{");
for (int i = 0; i < this.Rows; i++)
{
matrixString.Append("{");
for (int j = 0; j < this.Columns; j++)
{
if (j == 0) comma = "";
else comma = ",";
matrixString.Append(comma + this.Elements[i, j].ToString());
}
matrixString.Append("}");
}
matrixString.Append("}");
return matrixString.ToString();
}
In the above code:
- this.Elements Property: in the Matrix class, this is a 2-dimensional array of Int32 type (Double in a newer, more advanced version); it is of System.Numerics.Complex type in ComplexMatrix
- this.Rows, this.Columns Properties: the number of rows and columns respectively of the matrix
Several questions I have are:
- When ToString is called on a ComplexMatrix instance, and calls the base ToString() method, is an attempted type conversion taking place from Complex to Int32?
- As the ComplexMatrix Elements property (Complex[,] type) is hiding the base class Elements property (Int32[,] type), the new keyword is required?
- Is the “this” kwyword being seen as a Matrix type rather than ComplexMatrix?
I think your problem is the following:
The
Elementsproperty is not markedvirtualin theMatrixclass. TheElementsproperty in theComplexMatrixclass hides theElementsproperty of theMatrixclass. Therefore polymorphism isn’t working and theToStringmethod inMatrixaccessesMatrix.Elementsand notComplexMatrix.Elements. But becauseElementsis a property and you want to change the type of the property, you can’t usevirtualanyway.To fix the problem, you should do something like this:
SimpleMatrixclass that inherits from this base class and passesintas generic parameter.ComplexMatrixclass that inherits from this base class and passesComplexas generic parameter.