Suppose we have an idea for the general class Matrix<T> , where T is a numeric type ( Complex or double or float , int , etc.).
Naturally, we have implicit conversions in C # from float to double , from double to Complex . The general rule is that we have an implicit conversion from a smaller type to a larger one. So far so good.
Now imagine that we are implementing our type Matrix<T> . Since this new type is also in some sense numerical (or at least it contains numerical values), it is natural to have implicit conversions from Matrix<float> to Matrix<double> , from Matrix<double> to Matrix<Complex> and t .d. At the very least, it is nice to have them for mathematical operations such as multiplication, addition, etc. However, this seems impossible for proper implementation because the implicit operator requires that at least one type be the same as the class in which we implement it.
Example: the code below does not compile even though it may solve my problem.
public abstract partial class Matrix<T> { /// <summary> /// Implicitly converts a matrix to double precision complex numbers. /// </summary> public static implicit operator Matrix<Complex64>(Matrix<double> matrix) { matrix.ToComplex(); } /// <summary> /// Implicitly converts a matrix to double precision real numbers. /// </summary> public static implicit operator Matrix<double>(Matrix<float> matrix) { matrix.ToDouble(); } }
It will not compile because "CS0556 user-defined conversion must convert to or from the closing type" and let it say that I am fine with it because it is part of the language specification, but there should not be another way to achieve this?
For example, this also does not compile.
public abstract partial class Matrix<double> { /// <summary> /// Implicitly converts a matrix to single precision real numbers. /// </summary> public static implicit operator Matrix<double>(Matrix<float> matrix) { matrix.ToDouble(); } }
Is there a way to achieve this, it feels natural, so I think it should be achievable?
At the moment, I have created a workaround solution that allows implicit conversion for all types to the largest, but does not allow conversion from Matrix<float> to Matrix<double> , it only allows Matrix<Complex> conversions.
public abstract partial class Matrix<T> {
If anyone is interested in the background around this issue, you can take a look at https://github.com/mathnet/mathnet-numerics/issues/304
Another solution to this could be to use something like “extension operators” (similar to extension methods), but they are not present in C #.