I'm trying to create a measurement library in c# with compile-time checking of dimensions (length, time, ec.) Adding and subtracting are easy because they both used the same dimensions. However, when multiplying two scalars, the resulting Dimension (which I've used as the generic type), needs to be determined at run-time. Eg. Length x Length = Area, Area X Length = Volume, etc.
I'm only experimenting at this stage, but how would you resolve this problem (see below in method Times). The problem is that it can't convert from Area to Q in the return types.
public abstract class Dimension
{ }
public class Length : Dimension
{ }
public class Mass : Dimension
{ }
public class Area : Dimension
{ }
public class Scalar<T> : Measure<T> where T : Dimension
{
private float amount;
public Scalar(float amount)
{
this.amount = amount;
}
public static Scalar<T> operator +(Scalar<T> A, Scalar<T> B)
{
return new Scalar<T>(A.amount + B.amount);
}
public static Scalar<T> operator -(Scalar<T> A, Scalar<T> B)
{
return new Scalar<T>(A.amount - B.amount);
}
public Scalar<Q> Times<S>(Scalar<S> that)
where Q : Dimension
where S : Dimension
{
return new Scalar<Area>(this.amount * that.amount);
}
public override string ToString()
{
return "" + amount;
}
}