public static Byte DivideBy(this Byte thisByte, Byte divisor, Byte valueIfError = 0)
{
return divisor != 0 ? (Byte)(thisByte / divisor) : valueIfError;
}
public static SByte DivideBy(this SByte thisSByte, SByte divisor, SByte valueIfError = 0)
{
return divisor != 0 ? (SByte)(thisSByte / divisor) : valueIfError;
}
public static Int16 DivideBy(this Int16 thisInt16, Int16 divisor, Int16 valueIfError = 0)
{
return divisor != 0 ? (Int16)(thisInt16 / divisor) : valueIfError;
}
public static UInt16 DivideBy(this UInt16 thisUInt16, UInt16 divisor, UInt16 valueIfError = 0)
{
return divisor != 0 ? (UInt16)(thisUInt16 / divisor) : valueIfError;
}
public static Int32 DivideBy(this Int32 thisInt32, Int32 divisor, Int32 valueIfError = 0)
{
return divisor != 0 ? (Int32)(thisInt32 / divisor) : valueIfError;
}
public static UInt32 DivideBy(this UInt32 thisUInt32, UInt32 divisor, UInt32 valueIfError = 0)
{
return divisor != 0 ? (UInt32)(thisUInt32 / divisor) : valueIfError;
}
public static Int64 DivideBy(this Int64 thisInt64, Int64 divisor, Int64 valueIfError = 0)
{
return divisor != 0 ? (Int64)(thisInt64 / divisor) : valueIfError;
}
public static UInt64 DivideBy(this UInt64 thisUInt64, UInt64 divisor, UInt64 valueIfError = 0)
{
return divisor != 0 ? (UInt64)(thisUInt64 / divisor) : valueIfError;
}
public static Single DivideBy(this Single thisSingle, Single divisor, Single valueIfError = 0)
{
if ((divisor != 0) && thisSingle.IsValid() && divisor.IsValid())
{ return thisSingle / divisor; }
else
{ return valueIfError; }
}
public static Double DivideBy(this Double thisDouble, Double divisor, Double valueIfError = 0)
{
if ((divisor != 0) && thisDouble.IsValid() && divisor.IsValid())
{ return thisDouble / divisor; }
else
{ return valueIfError; }
}
public static Decimal DivideBy(this Decimal thisDecimal, Decimal divisor, Decimal valueIfError = 0)
{
return divisor != 0 ? (Decimal)(thisDecimal / divisor) : valueIfError;
}
public static bool IsValid(this Single thisSingle)
{
return !(Single.IsInfinity(thisSingle) || Single.IsNaN(thisSingle));
}
public static bool IsValid(this Double thisDouble)
{
return !(Double.IsInfinity(thisDouble) || Double.IsNaN(thisDouble));
}
.
.
.
The DivideBy method makes it easy to handle divide by error handling if the a number like zero is preferred instead of an exception:
.
.
.
double valueA = 30;
double valueB = 0;
double valueC = double.NAN;
double result = valueA.DivideBy(valueB); // Returns default of zero instead of an exception.
double result = 500.DivideBy(valueC); // Returns default of zero instead of an exception.
double result = 20000.DivideBy(valueA, -1); // Return -1 as an invalid indicator
if (valueB.IsValid())
{
// IsValid tests for IsInfinity and IsNaN to ensure that the double value is valid for other operations.
}