I'm currently trying to write an extension method to work out the allowed variance for a decimal. While I was writing it I thought I'd extend it to a generic extension, with restrictions to decimal, float, double.
Currently I'm not aware of how (or if it's possible) to restrict a generic to value types.
public static bool WithinVariance(this decimal source, decimal allowedVariance, decimal comparisonValue)
=> WithinVariance<decimal>(source, allowedVariance, comparisonValue);
public static bool WithinVariance<T>(T source, T allowedVariance, T comparisonValue)
// where T : decimal
// where T : double
// where T : float
{
var allowedDifference = (source / 100) * allowedVariance;
var difference = source - comparisonValue;
return Math.Abs(difference) <= allowedDifference;
}
The above code doesn't work, it's there purely to show the approach I'm taking. Originally I was just going to a single method, but I changed to the above to try to hack it into working. Also an attempt at restricting the extension methods without using a where t filter (see commented out lines)
Does anyone know if it's possible and if so how to do this?