I am writing two classes in C#:
- A
Matrix
class that represents a general Matrix with n-by-m dimensions - A
SquareMatrix
class that inherits fromMatrix
and has the constraint of being n-by-n
The reason I designed it this way is because square matrices support additional specific operations like calculating the determinant or the inverse, so being able to guarantee that those functions are avaliable with the specific type you're using are nice things to have. Additionally it would support all the regular Matrix operations and can be used as a Matrix
I have a function in Matrix
called getTranspose()
. It calculates the transpose of the Matrix and returns it as a new Matrix
I inherited it in SquareMatrix
, but because the transpose of a square matrix is guaranteed to be square matrix, I also want it to return a SquareMatrix
I am unsure about the best way to do this.
- I can re-implement the function in
SquareMatrix
, but that would be code duplication because it's essentially the same calculation - I can use implicit typecast operators, but if I understand correctly that would cause unnecessary allocations (upcast
SquareMatrix
toMatrix
, create a newMatrix
as the transpose, create a newSquareMatrix
during typecasting and throw away the tranposedMatrix
) - I can use explicit typecast operators, but it would be stupid to have to typecast the transpose of a
SquareMatrix
explicitly, and it also has the same problem of the implicit operator with unnecessary allocations
Is there another option? Should I change the design of having SquareMatrix
inherit from Matrix
?
This problem also applies to operators. It seems that I have to either implement typecasting operators which might cost in performance, or have to re-implement the same code.
getTranpose()
fromMatrix
, which I'm trying to avoid.