Looking for some advice regarding Infinity/-Infinity in C#.
I'm currently building Geometry classes, for shapes like Rectangle/Circle etc. The user will provide the input for Width/Depth and Diameter respectively.
These properties will be double
and I understand that instead of explicitly overflowing, if you were to multiple double.MaxValue
by 2, then you would get +infinity etc.
Each of the shape classes will have additional properties such as Area, Perimeter etc. Therefore, even if the provided dimensions are less than MaxValue, there is a chance that computed values could be a huge number if the user was so inclined:
E.g. Math.PI x Math.Pow(diameter, 2) / 4
=> Math.PI x Math.Pow(double.MaxValue, 2) / 4
(i.e. This method would result in +infinity even though the user provided MaxValue as input.)
My question is whether I should always be guarding against infinity? Should I throw an exception (OverflowException) if either the user value or the computed values enter infinity?
It looks like it could be a code smell to check for infinity for every property/method in these geometric classes... Is there a better way?
public double Area
{
get
{
double value = Math.PI * Math.Pow(this.diameter, 2) / 4;
if (double.IsInfinity(value)
{
throw new OverflowException("Area has overflowed.");
}
}
}
public double Perimeter
{
get
{
double value = Math.PI * this.diameter;
if (double.IsInfinity(value)
{
throw new OverflowException("Perimeter has overflowed.");
}
}
}
Appreciate your time and thoughts! Cheers.