I need to use an unsigned double but it turns out C# does not provide such a type.
Does anyone know why?
As pointed out by Anders Forsgren, there is no unsigned doubles in the IEEE spec (and therefore not in C#).
You can always get the positive value by calling Math.Abs() and you could wrap a double in a struct and enforce the constraint there:
public struct PositiveDouble
{
private double _value;
public PositiveDouble() {}
public PositiveDouble(double val)
{
// or truncate/take Abs value automatically?
if (val < 0)
throw new ArgumentException("Value needs to be positive");
_value = val;
}
// This conversion is safe, we can make it implicit
public static implicit operator double(PositiveDouble d)
{
return d._value;
}
// This conversion is not always safe, so we make it explicit
public static explicit operator PositiveDouble(double d)
{
// or truncate/take Abs value automatically?
if (d < 0)
throw new ArgumentOutOfRangeException("Only positive values allowed");
return new PositiveDouble(d);
}
// add more cast operators if needed
}